javascript - 关于获取元素样式的兼容性写法为什么不行呢?
本文介绍了javascript - 关于获取元素样式的兼容性写法为什么不行呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
div { width:100px; height:120px; background:red; }
</style>
<!--<script src="miaov.js"></script>-->
<script>
function $( v ){
if( typeof v === 'function' ){
return window.onload = v;
//console.log(v)
} else if ( typeof v === 'string' ) {
return document.getElementById(v);
} else if ( typeof v === 'object' ) {
return v;
}
}
$(function(){
// $('div1').style.width = '300px';
$('btn1').onclick = function (){
//var aaa=getComputedStyle( $('div1')).width || $('div1').currentStyle.width
var aaa= $('div1').currentStyle.width || getComputedStyle( $('div1')).width
***//在这里用申明变量的方式写了ie和chrome的获取元素样式的写法,为什么会报错的?备注:这里用的$不是jquery,而是上面定义的$函数***
alert(aaa)
};
});
</script>
</head>
<body>
<input id="btn1" type="button" value="按钮" />
<div id="div1"></div>
</body>
</html>
解决方案
你思路是没啥问题,但是细节有点问题。
你是想||运算符,返回其中一个为真的,但是它只能用来处理真假,而错误不能算是假。
$('div1').currentStyle 返回的是一个undefined,你再取他的属性,自然是报错。||不能判断错误。
你可以先判断,再取width的值。
var aaa= $('div1').currentStyle || getComputedStyle( $('div1'));
var aaaa = aaa.width;
这篇关于javascript - 关于获取元素样式的兼容性写法为什么不行呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文