【发布时间】:2019-09-10 22:14:13
【问题描述】:
我正在尝试将translateX() 属性赋予被称为this.firstClone 作为javascript 的克隆元素。问题是this.firstClone 没有引用克隆的元素,即使值本身在代码中进行了克隆。
constructor($el) {
this.$el = $el; // 0
this.myCards = this.$el.find('a'); // 1
this.myCount = 1; // 2
this.myLength = this.myCards.length; // 3
this.firstClone = this.myCards.first().before(this.myCards.last().clone().addClass('cloned')); // 4 this makes the clone.
this.lastClone = this.myCards.last().after(this.myCards.first().clone().addClass('cloned'));
}
在上面,this.firstClone 将最后一个图像克隆为集合中的第一个图像。而且当我删除它时,克隆的元素就消失了。制作、设置或删除克隆图像没有问题。
但是当我 console.log 它时,它指的是 DOM 中具有 translateX(1%) 的第二个元素。当我这样做时,该属性也将设置为第二个元素:this.firstClone.style.transform = "translateX(" + (-1) + "%)";
这是 javascript 的故障吗?还是我只是误解了.first() 和.clone() 方法?
我的目标是为每个克隆的元素赋予 css 属性,但我卡在这里没有任何线索。
完整代码:
'use strict';
(function ($, window, undefined) {
$.fn.cardSlider = function(options) {
return this.each(function() {
const $el = $(this);
var thatCards = new Card($el, options);
thatCards.scrolling($el);
})
}
class Card {
constructor($el) {
this.$el = $el; // 0
this.myCards = this.$el.find('a'); // 1
this.myCount = 1; // 2
this.myLength = this.myCards.length; // 3
this.firstClone = this.myCards.first().before(this.myCards.last().clone().addClass('cloned')); // 4 this makes the clone.
this.lastClone = this.myCards.last().after(this.myCards.first().clone().addClass('cloned'));
}
scrolling($el) {
console.log(this.firstClone);
this.firstClone.style.transform = "translateX(" + (-1) + "%)"; // Browser fires an error. Cannot set property 'transform' of undefined
this.firstClone.css({
paddingBottom: 200 + 'px'
}); // An example for proving that the css property doesn't refer to the real clone.
for (var i = 0; i < this.myLength; i++) {
this.myCards[i].style.transform = "translateX(" + Math.pow(2, i) + "%)";
}
}
}
}(jQuery));
$('.outer').cardSlider();
.outer {
margin: 0 auto;
width: 70%;
overflow: hidden;
}
.film {
display: flex;
flex-flow: row;
justify-content: center;
left: 90%;
}
.images {
position: relative;
display: block;
width: 90%;
flex-shrink: 0;
padding-bottom: 74%;
background-color: blue;
}
.images:first-child, .images:last-child {
background-color: orange;
opacity: .4;
}
<div class="outer">
<div class="film">
<a class="images" href="#" draggable="false"></a>
<a class="images" href="#" draggable="false"></a>
<a class="images" href="#" draggable="false"></a>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
*我在 Codepen 和这里测试了这段代码,但都没有工作。您可能必须制作新文件来测试它。
【问题讨论】:
-
你有什么理由这样构造你的代码吗?使用
init数组而不是单个变量?我觉得很难读。 -
@TheBlackIPs 我想将其分组并分开以使其看起来更好更清晰,但现在似乎不再。
-
没关系,我错了。
myCards.first().before()不会修改myCards。 -
如果您想将它们分组,请使用对象。然后你可以写
this.init.holder、this.init.cards等。这比this.init[1]这样的幻数更容易理解。 -
@l3lue 您用这种分组策略引入的问题被称为“神奇值”。当您谈论
init[4]时,没有人知道您的意思。数字 4 是任意的。你应该给你的变量起一个不言自明的名字(你在声明它们时已经这样做了)。
标签: javascript jquery html css class