gpt4 book ai didi

javascript - 需要帮助根据元素的宽度定位元素 (Javascript)

转载 作者:行者123 更新时间:2023-11-30 19:22:44 25 4
gpt4 key购买 nike

我正在开发一个步进器 UI,“前进”似乎效果很好。从“第 3 步”向后退,定位似乎偏离了。我想我针对的是错误的元素,但我不确定。

感谢任何帮助。代码笔:https://codepen.io/abenjamin/pen/aepMEW?editors=1111

HTML

<div class="stepper-ui">
<figure class="bar"><div class="line"></div></figure>
<ul class="progress-stepper">
<li class="step active">Overview</li><li class="step">Shipping</li><li class="step">Payments</li><li class="step">Returns</li><li class="step">Contacts</li>
</ul>
</div>
<button id="next" onclick="regress()">Back step</button>
<button id="next" onclick="progress()">Next step</button>

JS

function regress(){

// Look for the active step
let activeStep = document.querySelector('.active');

// Look for the previous step
let previousStep = activeStep.previousSibling;

// Get the width of the element
stepWidth = stepWidth - previousStep.clientWidth - 32;

// Step backwards
stepPlace--;

// Count the steps
let stepCount = document.getElementsByClassName('step').length;
// Calculate the new width of the meter

meterWidth = ((100/stepCount)*stepPlace);
// Update the styling to show the new meter width
progressMeter.style.cssText = "width:"+meterWidth+"%;"
// Slide the text to the left using the width of the step element
steps.style.cssText = "transform:translateX("+(stepWidth)+"px);"
// Remove the .active class from the active step
activeStep.classList.remove('active');
// Add the .active class to the newly active step
previousStep.classList.add('active');
console.log(stepWidth);
};

最佳答案

您需要在 translate 属性上保留减号

function regress(){

// Look for the active step
let activeStep = document.querySelector('.active');

// Look for the previous step
let previousStep = activeStep.previousSibling;

// Get the width of the element
stepWidth = stepWidth - previousStep.clientWidth - 32;

// Step backwards
stepPlace--;

// Count the steps
let stepCount = document.getElementsByClassName('step').length;
// Calculate the new width of the meter

meterWidth = ((100/stepCount)*stepPlace);
// Update the styling to show the new meter width
progressMeter.style.cssText = "width:"+meterWidth+"%;"
// Slide the text to the left using the width of the step element
steps.style.cssText = "transform:translateX(-"+(stepWidth)+"px);" // <-- here
// Remove the .active class from the active step
activeStep.classList.remove('active');
// Add the .active class to the newly active step
previousStep.classList.add('active');
console.log(stepWidth);
};

关于javascript - 需要帮助根据元素的宽度定位元素 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com