2

我的网站上有多个部分在背景上提供“视差”样式效果,这在许多移动平台上被禁用。

我想使用一些 jQuery 或 javascript 来"background-attachment:fixed"替换"background-attachment: scroll".

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

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

4

3 回答 3

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 小提琴 2

if(isMobile) {
    $('.bg').css({'background-attachment':'scroll'});
}
  • 请注意,如果它是移动的,isMobile则可能是您触发的变量,true具体取决于userAgent窗口宽度
于 2016-01-23T20:44:22.667 回答
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";
      }
    }
}

我没有测试过这个,我怀疑它不会解决你的问题,因为你没有一个类名。你也可以在 all divs 或其他东西上运行它。

于 2016-01-23T20:42:33.490 回答
0

下面的片段

//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)
}

}
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;

}
<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>

于 2016-01-23T20:56:04.560 回答