首页 > 解决方案 > 如何在javascript或jquery中以百分比设置html元素位置

问题描述

我正在尝试将 div 的位置设置为身体的 100%。然而,它需要在 JavaScript(或 jQuery)中完成。

这就是我想象的代码的样子......

const div = document.getElementById("div");
div.style.right = 100 + "%";

任何让我研究的信息或文件将不胜感激,谢谢。为了澄清起见,我想将 div 移动到身体的右侧,但我想在 javaScript 中以百分比形式进行。

标签: javascripthtml

解决方案


You are looking for the width CSS property to set to 100%.

const div = document.getElementById("div");
div.style.width = "100%";
<div id="div" style="border: 1px solid black;"></div>

However, with the div tag, explicitly making its width 100% is unnecessary as it is a block level element (having display: block) and will automatically inherit the width of its parent.

For a progress bar, you just need to set its width to 0% at the start and gradually increase the width with a setInterval. Reference: https://www.w3schools.com/howto/howto_js_progressbar.asp

.progress {
  width: 100%;
  background-color: #ddd;
}

.bar {
  width: 0%;
  height: 20px;
  background-color: #4CAF50;
}
<div class="progress">
  <div class="bar"></div>
</div>
<p/>
<button onClick="run()">Start</button>
<script>
var bar = document.querySelector('.bar');
function run(){
var width = 0;
var intvl = setInterval(function(){
   width ++
   bar.style.width = width + "%";
   if(width>=100){
    clearInterval(intvl);
   }
}, 10);
}
</script>


推荐阅读