javascript - 如何在javascript或jquery中以百分比设置html元素位置
问题描述
我正在尝试将 div 的位置设置为身体的 100%。然而,它需要在 JavaScript(或 jQuery)中完成。
这就是我想象的代码的样子......
const div = document.getElementById("div");
div.style.right = 100 + "%";
任何让我研究的信息或文件将不胜感激,谢谢。为了澄清起见,我想将 div 移动到身体的右侧,但我想在 javaScript 中以百分比形式进行。
解决方案
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>
推荐阅读
- python - AttributeError:“工作表”对象没有属性“set_column”
- math - 数学问题在子视图中划分视图
- javascript - 如何找到属性值的最小值和最大值
- php - 错误:类 'MailchimpMarketing\ApiClient'
- azure-active-directory - Blazor WASM - AzureAD 身份验证 - HttpContext.User.Claims 是空的?
- java - 如何让用户能够通过使用扫描仪功能无限输入键盘来输入内容?
- python - 不同模块中的相同导入是否“堆叠”在内存中?
- r - 使用来自 Shiny 模块的数字输入值作为用户定义函数的输入,并使用该函数的输出作为另一个模块中的输入
- python - 如何使用 pytest 设备优雅地模拟一个类?
- terminal - 终端问题,MicroPythonREPL