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

本文详细介绍了使用原生JavaScript和jQuery来获取与修改HTML元素样式的技巧。通过具体实例展示了如何利用这两种方式来动态调整页面元素的透明度、边框颜色等属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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]; 先获取到一个img
console.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修改内嵌样式需要复写内嵌样式 然后保存至行内样式中




记录下来是怕自己又忘记了 写得有点乱 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值