原生style 与 jquery 获取修改元素总结

来源:互联网 发布:北通 手柄 知乎 编辑:程序博客网 时间:2024/04/30 15:02
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="javascripts/http_code.jquery.com_jquery-2.0.0.js"></script>    <style>        img{            width:100%;            height: 100%;            border: 1px solid;        }    </style></head><body><img src="images/b1_01.png" alt="" style="opacity: 0.2"><script>//    var img = document.getElementsByTagName("img")[0];//    console.log(img.style);//只能获取到行内的style//    img.style.opacity=1;//动态添加到内联标签//    img.style.borderColor = "red";//动态添加到内联标签//////    console.log(window.getComputedStyle(img,null).width);//能查询到内嵌style样式不能修改//    //console.log(img.currentStyle.width);//////    jquery  无论是内联还内嵌 style都可以获取和修改//    var $img = $("img");//    console.log($img.css("opacity"));//    console.log($img.css("width"));////    $img.css("opacity",1);//    $img.css("width","1000px");</script></body></html>
1、首先说一说原生js怎样获取与修改元素

修改
var img = document.getElementsByTagName("img")[0]; 先获取到一个imgconsole.log(img.style)  //此时获取到了元素的内联style  opacity此时可以修改opacity的值 比如:img.style.opacity = 1;opacity由0.2变成了1;所以:
<img src="images/b1_01.png" alt="" style="opacity: 1">在比如:
img.style.borderColor = "red";
<img src="images/b1_01.png" alt="" style="opacity: 1;borderColor="red"">直接动态添加到了行内。。。。当然还可以添加其他属性或者复写内嵌样式中的属性至行内样式中获取
console.log(img.style);//获取到行内的style 并且能够修改
console.log(window.getComputedStyle(img,null).width);//能查询到内嵌style样式但是不能修改  除了IE
console.log(img.currentStyle.width);//IE获取内嵌style样式 但也不能修改

img.style.opacity=1
img.style.width="1000px";//复写内嵌样式中的属性至行内样式
2、说一说jquery获取与修改元素
 var $img = $("img");
    console.log($img.css("opacity")); //获取到行内style    console.log($img.css("width"));//获取到内嵌style    $img.css("opacity",1);//修改行内style    $img.css("width","1000px");//修改内嵌style********jquery 无论是行内style还是内嵌style 都能直接获取 和 修改********jquery比原生js方便   原生js修改内嵌样式需要复写内嵌样式 然后保存至行内样式中记录下来是怕自己又忘记了 写得有点乱                                              
0 0
原创粉丝点击