sel 改变 border blue 实现 round document selector
看了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.bubuko.com/infodetail-2288690.html