【发布时间】:2015-06-14 23:46:34
【问题描述】:
我的想法是当我点击按钮时,div#x 将失去 1% 的宽度。这是我的代码:
document.querySelector('#a').onclick = function() {
var
lost = document.querySelector('#x').style.width,
lost = lost.slice(0, -1);
lost = Number(lost);
lost -= 1;
document.querySelector('#x').style.width = lost + '%';
}
nav#control {
display: flex;
flex-basis: 50px;
align-items: center;
justify-content: center;
background: #FFF;
padding: 5px;
width: 100%
}
.knob {
display: flex;
align-items: center;
justify-content: center;
width: 40px; height: 40px;
cursor: pointer
}
#b {
position: relative;
flex-grow: 1;
background: #EFEFEF;
margin: 0 10px;
height: 30px
}
#x {
position: absolute;
background: #4C8EFA;
width: 100%; height: 30px;
border-radius: 1px;
z-index: 2
}
#c {
display: flex;
align-items: center;
justify-content: center;
height: 30px;
}
<nav id='control'>
<section id='a' class='knob'><img src='x.png'/></section>
<section id='b'>
<div id='x'></div>
<div id='c'>background</div>
</section>
<section id='d' class='knob'><img src='x.png'/></section>
</nav>
每次单击左侧按钮 (section#a) 时,蓝色条 (div#x) 应该会缩短 1%。我检查了很多次,但我仍然不知道我的代码有什么问题。我确实更改了一些代码,我认为问题出在lost = document.querySelector('#x').style.width 这一行,因为它似乎没有返回任何应该给100% div#x 宽度的值
【问题讨论】:
-
什么是
catchID()? -
不幸的是,
style.width没有给出来自 CSS 的百分比。 -
.style对象仅具有直接应用于元素的样式。 CSS 规则隐含的样式将不可用。 -
@Blazemonger 我的错,catchID() 只是我自己获取 ID 元素的函数。我已经修复了正确的代码。
-
@jwatts1980 我确实尝试过w3schools.com/jsref/prop_style_width.asp,它与其他 HTML 代码配合得很好。
标签: javascript html css javascript-events