基于CSS类(Loop/Foreach)的条件样式



我完全被我的方法卡住了。我希望有人能帮我重新上路:(

我想要实现的是:当页面上的图像高度为<图像应该获得最小高度,并基于从左到右和向后的反弹/移动。我真的不知道在这种情况下最好的方法是什么。我可以访问来源,所以我可以进行一些调整。这是一个基于Wordpress的网站btw.

我有一个投资组合,在概述中有多个图像。为了保持图像的外观,其中一些图像被缩小了很多,看起来不太花哨:-D(有时图像只占空间的1/8(

  • 概览中的图像没有自己的标识符
  • 概览中的图像属于同一类

我的直觉是,我必须循环浏览所有的图像,并在它们满足某些条件时对它们采取一些行动。假设实际高度必须至少为70%(最可取(,否则它(或它的父级/容器(应该得到一个触发动画(CSS(的特定类。

在我现在所处的位置,条件语句结果被应用于包含给定类的每个元素。因此,这导致了我脑海中的404号:-D

这是我的代码:

$(document).ready(function(){
var myImg = document.querySelector(".animated img");
var currWidth = myImg.clientWidth;
var currHeight = myImg.clientHeight;

// alert("Current width=" + currWidth + ", " + "Original height=" + currHeight);
if (currHeight < 100) {
$(".animated img").addClass( "animated-image" );
}
});
* {
box-sizing: border-box;
}
html {
font-size: 16px;
}
.mt-2 {
margin-top: 0.5rem;
}
.bounce-container {
height: 400px;
}
.animated img {
max-width: 100%;
}
.animated, .portfolio-item {
position: relative;
/* background-color: pink; */
border: 1px solid #CCC;
line-height: $height;
/* max-width: 200px; */
overflow: hidden;
/* height: 200px; */
height: 100%;
text-align: center;
}
.animated-image {
position: absolute;
animation: 8s bounce ease-in-out infinite paused;
white-space: nowrap;
top: 0;
padding: 0 0.5rem;
max-width: 100%;
}
.animated .animated-image {
max-width: initial;
}
.animated:not(.animated--on-hover) .animated-image,
.animated.animated--on-hover:hover .animated-image {
animation-play-state: running;
}
@keyframes bounce {
0%, 45%, 95%, 100% {
left: 0%;
transform: translate(0, 0);
}
45%, 55% {
left: 100%;
transform: translate(-100%, 0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row bounce-container">
<div class="col-md-4 mt-2">
<div class="animated portfolio-item">
<img class="" src="https://www.hielke.net/wp-content/uploads/logo-handelbijvanandel-vpadding-1024x232.jpg">
</div>
</div>
<div class="animated col-md-4">
<img class="" src="https://www.hielke.net/wp-content/uploads/schotelexpert-featured-1024x1024.jpg">
</div>
<div class="animated col-md-4">
<img class="" src="https://www.hielke.net/wp-content/uploads/logo-handelbijvanandel-vpadding-1024x232.jpg">
</div>
</div>

链接到jsfiddle

我希望有人能/会给我指明正确的方向:(

您的代码中有一些问题导致了这种情况。。。

首先,您使用的是普通的JSdocument.querySelector(),它只选择第一个匹配的元素,而不是所有匹配的.animated img元素。然后将animated-image类添加到每一个.animated img元素中,而不管它的高度如何。

由于您的示例使用了一些jQuery,我将在这里坚持使用它(可能最好是完全接受jQuery或完全接受vanillaJS,而不是混合和匹配(。您可以使用jQuery的each函数在jQuery中迭代多个对象:

$( ".animated img" ).each( function( index, element ){
// do stuff here
});

像这样的东西应该起作用:

$( ".animated img" ).each( function(index, element) {
if ($(this).height() < 100) {
$(this).addClass('animated-image'); 
} 
});

可以使用cssmin-height属性设置元素的最小高度。

最新更新