<!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 而不能获取到内嵌的style样式 若要获取到内嵌样式则:console.log(window.getComputedStyle(img,null).width);//除了IE 只能获取到值 不能在这里改变值 console.log(img.currentStyle.width);//IE获取 只能获取 不能改变值改变的话需要这样做(即复写内嵌样式):img.style.width=1000px 或 img.style.height=1000px 等等
img.style.opacity = 1; opacity有0.2变成1;<img src="images/b1_01.png" alt="" style="opacity: 0.2"> 转变成====> <img src="images/b1_01.png" alt="" style="opacity: 1"> 添加: img.style.borderColor = "red"; borderColor 由无到有 此时img变成<img src = "images/b1_01.png" alt="" style="opacity: 1;borderColor: red;"> **若要修改style内嵌样式则通过复写的方式将内嵌样式加入到行内样式 比如修改img内嵌样式的width样式 则: img.style.width="1000px"; 此时width加入到行内样式中<img src = "images/b1_01.png" alt="" style="opacity: 1;borderColor: red;width:1000px;">
2、说一说jquery的获取修改var $img = $("img"); console.log($img.css("opacity"));//获取到img的透明度 console.log($img.css("width"));//获取到img的宽度 $img.css("opacity",1);//重新设置opacity $img.css("width","1000px");//重新设置width
********原生js和jquery获取修改元素的区别:
无论是行内样式还是内嵌样式,jquery可以直接获取和修改
而原生js通过element.style.attr获取到行内的样式,若要获取内嵌样式则需要:window.getComputedStyle(element,null).attr或者element.currentStyle.attr 如果要修改内嵌样式 则通过element.style.attr来复写内嵌样式至行内样式
原生js和jquery获取修改元素
最新推荐文章于 2022-04-14 17:27:01 发布