簡體   English   中英

需要幫助根據寬度定位元素(Javascript)

[英]Need help positioning an element based on it's width (Javascript)

我正在開發一個步進器 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);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM