我正在处理一个 JavaScript 元素,我需要在摄氏度和华氏度之间切换。 HTML 在这里
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
这是 JavaScript 函数
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
给出了我使用的CSS
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
如果你想实时检查这个应用程序,这里是链接
Please click on this link to see app in running form
如果您访问上面的链接并检查,您会发现在第一次点击时切换不起作用。但是,当您第二次单击时,它就会开始正常工作。
最佳答案
它不起作用,因为此 if (fahrenheit.style.display === 'none')
将返回 NULL,因为元素上没有内联样式。此方法不会“查看”CSS,它仅适用于内联样式。你可以试试这个:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
在纯 JS 中检查 CSS 属性,或者您可以使用 JQuery,这将在一行代码中解决它。
关于javascript - onclick 在第一次点击时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395138/