JavaScript中的backgroundPosition的设置

在CSS中background-position有对值的设置有两种:一是用数值(绝对的),另一个使用百分比(相对的)。这两种方式会有不同的浏览器兼容问题(主要是IE和FF)。
基本代码如下
style="overflow-y:scroll;height:300px;"

<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>mag3</title> <link rel="stylesheet" type="text/css" href="http://blog.163.com/m13194695967_2/blog/reset.css"> <style> *{margin:0;padding:0;border:0;} .all{width:500px;height:500px;border:1px solid blue;margin:0 auto;/* text-align:center; */} .con{width:200px;height:200px;background:url("img/backpic7.jpg");} </style> </head> <body> <div class="all"> <div class="con" id="con"></div> </div> </body>

<script type="text/javascript"> var con=document.getElementById("con");

con.style.backgroundPosition=600+"px "+800+"px";

</script> </html>


1 用数值指定。
如: con.style.backgroundPosition=x+"px "+y+"px";
可以兼容所有的浏览器,但要
注意第一个“px ”中有一个空格
如:
con.style.backgroundPositionX=x+"px";con.style.backgroundPositionY=y+"px";
不兼容FF.

2用百分比指定。
如:
con.style.backgroundPosition=x%+y%;  
不兼容IE。
如:
con.style.backgroundPositionX=x%;
con.style.backgroundPositionY=y%;
不兼容FF。

为了能够在使用百分比指定backgroundPosition的left和top值时,兼容各个浏览器,所以针对FF写了一个JS的hack,并用了异常处理机制防止IE在不必要时报错。
代码部分更改如下

var isFF = !!navigator.userAgent.match(/firefox/i);//FF的hack try//异常处理 { if(isFF) { con.style.backgroundPosition="60%"+"80%"; } con.style.backgroundPositionX="60%"; con.style.backgroundPositionY="80%"; } catch (err) { }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值