星空网 > 软件开发 > Java

IE8和IE7如何获取background

IE8和IE7如何获取background-position属性值:
之所以要单独介绍一下如何获取background-position属性值,是因为在IE8和IE8以下浏览器中存在一定的兼容性问题,下面对此做一下简单介绍,希望能够给需要的朋友带来帮助。
一.使用style方式:
此方式只能够获取使用style方式定义的css样式属性,代码如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>蚂蚁部落</title> <style type="text/css">#thediv{ width:100px; height:100px; background-color:green;}</style><script type="text/javascript">window.onload=function(){ var thediv=document.getElementById("thediv"); thediv.innerHTML=thediv.currentStyle["backgroundPosition"];}</script> </head> <body> <div id="thediv" style="background-position:10px 20px">蚂蚁部落</div></body> </html>

以上代码在所有的主流浏览器都能够正确获取到background-position属性值,说明此种方式没有兼容问题。
二.获取样式表定义的属性:
如果css属性是在样式表中定义的,那么使用style方式就无能为力了,则需要更换方法,具体可以参阅getComputedStyle()和currentStyle属性的用法一章节,但是对于background-position属性要特别的小心,因为在IE8和IE8以下浏览器中并不支持backgroundPosition这种方式,而是支持backgroundPositionX和backgroundPositionY属性,所以要进行一下兼容性处理,代码如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>蚂蚁部落</title> <style type="text/css">#thediv{ width:100px; height:100px; background-color:green; background-position:10px 20px}</style><script type="text/javascript">function getStyle(obj,attr){ if(obj.currentStyle){  if(attr=="backgroundPosition"){   return obj.currentStyle.backgroundPositionX +" "+obj.currentStyle.backgroundPositionY;   }  else{   return obj.currentStyle[attr];  } } else{  return document.defaultView.getComputedStyle(obj,null)[attr];  }}window.onload=function(){ var thediv=document.getElementById("thediv"); thediv.innerHTML=getStyle(thediv,"backgroundPosition")}</script> </head> <body> <div id="thediv">蚂蚁部落</div></body> </html>

以上代码实现了我们的要求,可以实现各个浏览器兼容。
相关阅读:
1.getComputedStyle()和currentStyle可以参阅getComputedStyle()和currentStyle属性的用法一章节。
2.innerHTML属性可以参阅js的innerHTML属性的用法一章节。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=11712

更多内容可以参阅:http://www.softwhy.com/javascript/




原标题:IE8和IE7如何获取background

关键词:ie

ie
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

contactmonkey:https://www.goluckyvip.com/tag/17212.html
Content Explorer:https://www.goluckyvip.com/tag/17213.html
content26:https://www.goluckyvip.com/tag/17215.html
Contentbird:https://www.goluckyvip.com/tag/17216.html
Contentproz:https://www.goluckyvip.com/tag/17217.html
Converse:https://www.goluckyvip.com/tag/17218.html
深圳到西安自驾路线攻略 深圳到西安自驾最佳路线:https://www.vstour.cn/a/411228.html
松花蛋是哪里的特产松花蛋的产地:https://www.vstour.cn/a/411229.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流