css:当触发javascript onscroll事件时,悬停效果不再有效

时间:2017-01-11 16:30:41

标签: javascript html css

在javascript中我有onscroll事件,它根据window.pageYOffset移动div元素。在css中我有一个:hover,它应用transform:scale();

页面加载时,css效果有效。但是,只要开始滚动并应用onscroll事件,移动的div就不再响应悬停效果。没有滚动事件的div仍具有css效果。知道是什么导致了冲突吗?https://jsfiddle.net/kshatriiya/b2jxg3ep/1/

<div id="container">
  <div class="box" id="one"></div>
  <div class="box" id="two"></div>
  <div class="box" id="three"></div>
  <div class="box" id="four"></div>
  <div class="box" id="five"></div> 
</div>

<div id="scroll-container">
  <div class="box move" data-offset="12" id="six"></div>
  <div class="box move" data-offset="14" id="seven"></div>
  <div class="box move" data-offset="16" id="eight"></div>
  <div class="box move" data-offset="18" id="nine"></div>
  <div class="box move" data-offset="20" id="ten"></div>  
</div> 

JS

var boxes = document.getElementsByClassName("box");
var movingBoxes = document.getElementsByClassName("move");
var boxArray = [];

(function() {
for (var i = 0; i < boxes.length; i++) {
var r = Math.floor((Math.random() * 254) + 1);
boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";
}
})();

var boxItem = function(el, speed) {
this.el = el;
this.speed = speed;
this.startOffset = this.speed*10;
};

boxItem.prototype.update = function(Yoff) {

var spd = (Yoff)/(this.speed/(this.startOffset/10));
var distanceRemain = this.startOffset-spd;
if (distanceRemain < 0) {distanceRemain = 0};
this.el.style.transform = "translateY(" + distanceRemain + "px)";

}

function prepareArrays() { 
for (i = 0; i < movingBoxes.length; i++) {
boxArray.push(new boxItem(movingBoxes[i], movingBoxes[i].getAttribute("data-offset")));
};
}

prepareArrays();


window.onscroll = function() {
var Yoffset = this.pageYOffset;

boxArray.forEach(function(el){

el.update(Yoffset);

});
}

CSS

#container {
  width: 100vw;
  height: 200px;
  display: flex;
  flex-diretion: row;  
}

.box {  
 margin: 0;
 padding: 0;
 width: 20%;
 height: 100px;
 -webkit-transition: width 1s ease-out, transform 3s ease;
 -moz-transition: width 1s ease-out, transform 3s ease;
 -ms-transition: width 1s ease-out, transform 3s ease;
 -o-transition: width 1s ease-out, transform 3s ease;
 transition: width 1s ease-out, transform 3s ease;
 background: red;
}

.box:hover {
transform: scale(1.1, 1.1);
}

#scroll-container {

 width: 100%;
 height: 1000px;
 display: flex;
 flex-direction: row;
 justify-content: flex-start;
 align-content: flex-start;
}

2 个答案:

答案 0 :(得分:1)

您通过javascript应用的转换会覆盖悬停时的转换,因为通过js应用的样式是内联样式

答案 1 :(得分:1)

很明显,你在同一个元素上覆盖相同的CSS引用。

尝试从CSS !important转换中放置.box:hover,这样做就可以了解