如何替换背景附件:固定在手机上?

时间:2016-01-23 19:29:51

标签: javascript jquery html css background-attachment

我的网站上有各种各样的部分,它们对背景提供了“ parallax ”风格效果,在许多移动平台上都禁用了。

我想使用一些jQuery或javascript替换"background-attachment:fixed"的样式"background-attachment: scroll"的所有实例。

我并不热衷于手动更新每个位置(这是一个巨大的项目),我很高兴在手机上失去视差效果并回归到background-size: cover

没有发布任何代码,因为我不确定从哪里开始。

3 个答案:

答案 0 :(得分:3)

如果所有这些元素共享同一个类名,比如bg,那么它可能是这样的:

JS:JS Fiddle 1 - 我在纯javascript中忘记了for循环

if(isMobile) {
    var backgrounds = document.getElementsByClassName('bg');

    for(var i in backgrounds){
        backgrounds[i].style.backgroundAttachment = 'scroll';
    }
}

jQuery:JS Fiddle 2

if(isMobile) {
    $('.bg').css({'background-attachment':'scroll'});
}
  • 请注意isMobile可能是您触发true的变量,如果它是移动的,具体取决于userAgent或窗口宽度

答案 1 :(得分:0)

您可以执行类似

的操作
if (!window.matchMedia("(min-width: 800px)").matches) {  
    var items = document.getElementsByClassName("some_class");
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.style.backgroundAttachment == "fixed") {
          item.style.backgroundAttachment = "scroll";
      }
    }
}

我没有对此进行过测试,我怀疑它不能解决您的问题,因为您没有一个类名。您也可以在所有div或其他内容上运行它。

答案 2 :(得分:0)

下面的代码段

&#13;
&#13;
//find all elements
var elements=document.body.querySelectorAll('*');
//loop through all elements
for(var i=0;i<elements.length;++i){
  //find the inline or css style for each element
element_style=window.getComputedStyle(elements[i],null)||elements[i].currentStyle;
//if style matches fixed change style
  if(element_style.backgroundAttachment=='fixed'){
console.log(element_style.backgroundAttachment)
elements[i].style.backgroundAttachment='scroll';
    //alert box that show style has been changed
alert('this div background is now '+ element_style.backgroundAttachment)
}

}
&#13;
div{
  background-image:url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQARVdhCSrk0o1t6uon-TqIJYit7b6unGWMn_zJu2Tg0LkoEi4Kpg');
  background-repeat: no-repeat;
  background-attachment:fixed;
  background-size:50px;
  border:solid;
  width:500px;
  height:100px;
  overflow:scroll;

}
&#13;
<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>

<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>
<div>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
Something here <br>
</div>
&#13;
&#13;
&#13;