Javascript 当我在可滑动滑块&xBF;上显示新元素时,页面会变慢;我怎样才能解决这个问题?
我使用触摸事件制作了一个可滑动滑块,当可视元素中还有一个可见元素时,我要加载新元素,为此我使用以下方法:Javascript 当我在可滑动滑块&xBF;上显示新元素时,页面会变慢;我怎样才能解决这个问题?,javascript,css,dom,Javascript,Css,Dom,我使用触摸事件制作了一个可滑动滑块,当可视元素中还有一个可见元素时,我要加载新元素,为此我使用以下方法: initInteractionWithItems(elementsToMakeVisible) { let totalMargin = 0 //the items are stacked and in the loop, the margin gradually gets bigger let indexZ = 0 //the indexZ also gets bigg
initInteractionWithItems(elementsToMakeVisible) {
let totalMargin = 0 //the items are stacked and in the loop, the margin gradually gets bigger
let indexZ = 0 //the indexZ also gets bigger in the loop (is the z-index for the stacked elems)
const sizeItems = this.items.length
let styleElement = document.createElement("style")
document.head.appendChild(styleElement)
if (elementsToMakeVisible) {
firstInTheList.style.zIndex = "" + (elementsToMakeVisible + 1) * 1000
} else {
elementsToMakeVisible = this.itemsVisibleLength
}
totalMargin = this.marginTopFactor * elementsToMakeVisible
indexZ = elementsToMakeVisible * 1000
//while the list have elements, I show a portion of those
while ((elementsToMakeVisible !== 0) && (this.elementsCount < sizeItems)) {
let rule = ".swipeItem-" + this.elementsCount + "{ opacity: " + "1;" + "margin-top:" + totalMargin + "px;" + "z-index:" + indexZ + ";}"
this.items[this.elementsCount].classList.add("swipeItem-" + this.elementsCount)
totalMargin -= this.marginTopFactor
indexZ -= 1000
elementsToMakeVisible--
this.elementsCount++
styleElement.sheet.insertRule(rule)
}
}
}
function sendTarget(event) {
if (event.cancelable) {
canSlide = false
event.preventDefault()
if (!has_option_selected) { //if a element has been selected
event.target.offsetParent.style.transform = "rotateZ(0deg)"
} else {
firstInTheList.remove()
firstInTheList = iteratorItems.next().value
countElements--
if (countElements === 1) { //if in the slider remains only one element
swipeReference.initInteractionWithItems(2)
}
}
}
}
只有第一个元素具有触摸事件,每次选择一个元素时,我都会删除该元素,并且第一个元素将是我使用的数组中的下一个元素,因此我使用此生成器函数:
function* getFirstItem(arrayElements) {
for (let i = 0; i < arrayElements.length; i++) {
arrayElements[i].addEventListener("touchstart", getCoords, true)
arrayElements[i].addEventListener("touchmove", slideTarget, true)
arrayElements[i].addEventListener("touchend", sendTarget, true)
yield arrayElements[i]
}
}
文件
罗丝·安,19岁
玛丽·沃尔夫斯顿克拉夫特,24岁
罗斯·多伊,34岁
乔安妮·史密斯,34岁
玛丽·沃尔夫斯顿克拉夫特,24岁
太多的代码可以简化为短代码,或者在codesandbox或JSFIDLE上制作一个工作示例