js获取元素外链样式的方法

2019-12-18,,,,,,,

本文实例讲述了js获取元素外链样式方法。分享给大家供大家参考。具体分析如下:

一般给元素设置行内样式,如<div id="div1" style="width:500px;"></div>。如要获取它的样式,即可document.getElementById("div1").style.width来获取或设置。但是如果样式是在外链link中的或者是页面的非行内样式,就获取不到了。

在标准浏览器中可以通过window.getComputedStyll(obj,null)[property]来获取外链样式,但是在ie浏览器中则是通过obj.currentStyle来获取。

完整html代码如下:
复制代码 代码如下:<!DOCTYPE html>
<html>
<head>
<title>js获取元素外链样式</title><base target="_blank"/>
<style type="text/css">
p {
width: 500px;
line-height: 30px;
}
</style>
<script src="jquery/jquery-1.11.2.min.js">
</script>
<script>
function getstyle(obj,property){
if(obj.currentStyle){
return obj.currentStyle[property];
}else if(window.getComputedStyle){
return document.defaultView.getComputedStyle(obj,null)[property];//或者也可以通过window.getComputedStyle来获取样式
}
return null;
}

$(document).ready(function(){
$("p").click(function(){
alert(getstyle(this,"width"));
});
});
</script>

</head>
<body>
<p style="width:750px;">如果您点击我,弹出宽度。</p>
<p>点击我,弹出宽度。</p>
<p>也要点击我~O(∩_∩)O~。</p>

</body>
</html>

希望本文所述对大家的javascript程序设计有所帮助。

您可能感兴趣的文章:

  • 原生js获取元素样式的简单方法
  • js获取元素的外链样式的简单实现方法
  • JavaScript操作HTML元素和样式的方法详解
  • 原生javascript获取元素样式
  • JS获取和修改元素样式的实例代码

《js获取元素外链样式的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。