JavaScript中的backgroundPosition的设置

颛孙博易
2023-12-01
在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) { }


 类似资料: