【问题标题】:How do I use the input field in order to change the value of the css property by java script?如何使用输入字段通过 java 脚本更改 css 属性的值?
【发布时间】:2020-03-03 11:58:32
【问题描述】:

我想在输入字段中输入属性的值,例如颜色。

并且在新样式的另一个输入字段中是蓝色

let p_change = document.getElementById('p-change');
let property = document.getElementById('property').value; // each color ,fontSize
let newStyle = document.getElementById('style').value; 	// each  red , 20px
let change	 = document.getElementById('change');

change.onclick = function(){
	p_change.style.property = 'newStyle'; 
}
<p id="p-change">Change my style like you love</p>
		  		<input id="property" value="" placeholder="Enter Property">
				<input id="style" value="" placeholder="Enter New Style">
			  	<button id="change">Change</button>
enter image description here

【问题讨论】:

标签: javascript css dom input


【解决方案1】:

点击按钮后需要获取属性和样式。

如果你之前得到它们,它们是空字符串。

另外,使用const 而不是let。在这种情况下无需使用let

还添加了一个小验证,查看输入的property 是否存在。

const p_change = document.getElementById('p-change');
const change = document.getElementById('change');

change.onclick = function() {
  const property = document.getElementById('property').value
  const newStyle = document.getElementById('style').value;

  // extra verification
  const style = p_change.style
  const findPropertyArr = Object.keys(style).filter(key => key === property)
  if (findPropertyArr.length > 0) {
    p_change.style[`${property}`] = `${newStyle}`;
    document.getElementById('error').remove();
  } else {
    p_change.innerHTML += '<p id="error" style="color:red">Invalid property name</span>'
  }
}
<p id="p-change">Change my style like you love</p>
		  		<input id="property" value="" placeholder="Enter Property">
				<input id="style" value="" placeholder="Enter New Style">
			  	<button id="change">Change</button>

【讨论】:

  • 它适用于 let。但是 let 还有其他用例。当您更改该变量的值时,您基本上使用let。例如let errorMessage = ' Some error ' ,然后在您的代码中进一步向下if (a&gt; b) { errorMessage = ' Different error ' }
【解决方案2】:

选定的节点具有 style 属性,其中包含 css 属性。

let node = document.querySelector('#someid')
node.style.color = 'red'
node.style.fontSize = '40px'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多