【问题标题】:Dynamically manipulate element attributes using input controls?使用输入控件动态操作元素属性?
【发布时间】:2019-08-21 13:29:08
【问题描述】:
我想使用输入控件来动态操作元素。纯 JavaScript 或 jQuery 都可以。
src="https://www.w3schools.com/css/rock600x400.jpg" >
</br><br>
<form class="button" action="">
Width
<input class="button" type="number" value="300">
Height
<input class="button" type="number" value="400">
</form>
结果会是这样的:
【问题讨论】:
标签:
javascript
jquery
forms
dom
element
【解决方案1】:
您所要做的就是添加一些id 属性,在JavaScript 中获取对您元素的引用并更新图像样式oninput(当宽度或高度的值发生变化时)
let img = document.getElementById('img');
let width = document.getElementById('width');
let height = document.getElementById('height');
changeSize = () => {
img.style.width = `${width.value}px`;
img.style.height = `${height.value}px`;
}
<img id="img" src="https://www.w3schools.com/css/rock600x400.jpg" />
</br><br>
<form class="button" action="">
Width
<input id="width" class="button" type="number" value="300" oninput="changeSize()"> Height
<input id="height" class="button" type="number" value="400" oninput="changeSize()">
</form>