这只是一个简单的javascript代码,用于更改显示或背景,或者只是看看我是否可以使用javascript来更改css属性。
这是基于一个示例。
但是由于某些原因,我无法使用自己定义的js函数更改属性。
HTML代码
<div id="question"> testting javascript</div>
<button onclick="close()">Close</button>
JS代码
function close(){
document.getElementById("question").style.display = "none";
document.getElementById('question').style.backgroundColor = "#f3f3f3";
}
完整代码
<div id="question"> testting javascript</div>
<button onclick="close()">Close</button>
<script>
function close(){
document.getElementById("question").style.display = "none";
document.getElementById('question').style.backgroundColor = "#f3f3f3";
}
</script>
它可能由于以下两个原因而无法工作:
close()
函数永远不会暴露给主作用域。close
是关闭窗口的现有JavaScript方法:window.close
。下面的代码正在工作:
window.closeQuestion = function() {
document.getElementById("question").style.display = "none";
document.getElementById('question').style.backgroundColor = "#f3f3f3";
};
/*/ This is a way of having a full control over your JavaScript functions and events: /*/
document.getElementById('closeBtn').addEventListener('click', function() {
closeQuestion();
});
#question {
background : red;
}
<div id="question"> testting javascript</div>
<!-- This is lame: -->
<button onclick="closeQuestion()">Close</button>
<!-- This is better: -->
<button id="closeBtn">Close (better)</button>
无论如何,您都应该使用JavaScript处理事件。上世纪使用on*
属性是如此。请参阅addEventListener
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句