分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

关于修改css样式的几种js用法

发布时间:2023-09-06 01:08责任编辑:赖小花关键词:js

看了js也有一段时间了,对于修改css样式有很多种方式可以实现,今天做一个小小的总结吧。

首先写个例子

body部分

<div class="box"></div>
<inpiut id-"btn" type="button" value="按钮">

style部分

.box{ ???width: 100px; ???height: 100px; ???background: red; ???border: 1px solid blue;}

基本的内容写好了,那么我们如何改变呢?

方法一:简单粗暴直接(属性修改)

<script> ?????var btn = document.getElementById(‘btn‘); ?????var box = document.querySelector(‘.box‘); ?????box.onclick = function(){ ?????box.style.width = "200px"; ?????box.style.height = "200px"; ?????box.style.height = "pink";} </script> ???

方法二 : cssText

<script> ???var btn = document.getElementById(‘btn‘); ???var box = document.querySelector(‘.box‘); ???????btn.onclick=function(){ ???box.style.cssText = "width:200px;height:200px;background:pink"; ???};</script>

方法三: dom操作 setAttrbute

btn.onclick=function(){ ???????????box.setAttribute("style","width:200px; height:200px; background:pink");}

基本上是这种三种,但是如果想要优雅一些。

就直接封装函数吧

<script> ?????var btn = document.getElementById(‘btn‘); ?????var box = document.querySelector(‘.box‘); ?????box.onclick = setStyle; ?????function setStyle(){ ?

//方法1: ?????box.style.width = "200px"; ?????box.style.height = "200px"; ?????box.style.height = "pink"; ??
//方法2:
????box.style.cssText = "width:200px; height:200px; background:pink;";
//方法3:
   box.setAttrbute(‘style‘,"width:200px; height:200px; background:pink")}</script> ???????????

关于修改css样式的几种js用法

原文地址:http://www.cnblogs.com/weham/p/7467272.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved