滚动

时间:2017-12-06 09:48:28

标签: javascript jquery css animation clip-path

<script>     
$("flexbox.center").scroll(changeClass);

function changeClass() {
    if($("#coverphoto").hasClass('.coverphoto')){
        $("#coverphoto").removeClass("coverphoto").addClass("newshape");
    }
    else{
        $("#coverphoto").removeClass("newshape").addClass("coverphoto");
    }
}       
 </script>


clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
transition: 0.5s ease-in-out;
-----
clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
transition: 0.5s ease-in-out;

你好,

我的目标是在滚动时平滑地更改剪裁图像的形状。 我的方法是简单地在滚动时切换两个css属性,但这不起作用。 (顺便说一句,它完美地适用于:将鼠标悬停在最初的css属性上)

任何提示都受到高度赞赏,对我来说意义重大!

1 个答案:

答案 0 :(得分:1)

您的代码中存在错误,hasClass()函数不会选择选择器,只会选择类名:

&#13;
&#13;
function changeClass() {
  if ($("#cover").hasClass('coverphoto')) {
    $("#cover").removeClass("coverphoto").addClass("newshape");
  } else {
    $("#cover").removeClass("newshape").addClass("coverphoto");
  }
}
&#13;
.coverphoto {
  clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
  transition: 0.5s ease-in-out;
}

.newshape {
  clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
  transition: 0.5s ease-in-out;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
  <img src="https://lorempixel.com/400/150/">
</div>
<button onClick="changeClass()">change</button>
&#13;
&#13;
&#13;

顺便说一下,您只需使用toggleClass()

即可优化逻辑

&#13;
&#13;
function changeClass() {
  $("#cover").toggleClass("newshape");
}
&#13;
.coverphoto {
  clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
  transition: 0.5s ease-in-out;
}

.newshape {
  clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
  <img src="https://lorempixel.com/400/150/">
</div>
<button onClick="changeClass()">change</button>
&#13;
&#13;
&#13;

这是滚动事件的触发器:

&#13;
&#13;
$(document).scroll(function() {
  if ($(window).scrollTop() <= 150) {
    $("#cover").removeClass("newshape");
  } else {
    $("#cover").addClass("newshape");
  }
});
&#13;
body {
  height: 150vh;
}

.coverphoto {
  position: fixed;
  clip-path: polygon(0% 0%, 100% 0%, 100% 38.5%, 28.5% 65%, 0 65%);
  transition: 0.5s ease-in-out;
}

.newshape {
  clip-path: polygon(0% 0%, 100% 0%, 100% 53%, 41% 53%, 0 53%);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cover" class="coverphoto">
  <img src="https://lorempixel.com/400/150/">
</div>
&#13;
&#13;
&#13;