使用 Google+ Hangouts API,我正在尝试简单地切换 div 的可见性。它可以工作,但在触发之前需要单击两次(之后只需要来回单击一次)。这似乎是一个常见的切换问题,但解决方案总是不同的。也许很容易。帮助不大?谢谢!
<script>
//Fetches and displays participants
function showParticipants() {
var participants = gapi.hangout.getParticipants();
var retVal = '<p>Participants: </p><ul>';
for (var index in participants) {
var participant = participants[index];
if (!participant.person) {
retVal += '<li>A participant not running this app</li>';
}
retVal += '<li>' + participant.person.displayName + '</li>';
}
retVal += '</ul>';
//Toggles visibility of participantsDiv
var div = document.getElementById('participantsDiv');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
div.innerHTML = retVal;
}
function init() {
// When API is ready...
gapi.hangout.onApiReady.add(
function(eventObj) {
if (eventObj.isApiReady) {
document.getElementById('showParticipants')
.style.visibility = 'visible';
}
});
}
// Wait for gadget to load.
gadgets.util.registerOnLoadHandler(init);
</script>
最佳答案
我可以看到的一个可能的情况是,当您的 div 最初通过其他方式(例如使用 css)隐藏时。这种情况可能会发生,因为您的比较 if (div.style.display !== 'none')
将成功,因为 display 属性大部分为空或未定义(基于浏览器)并且它将应用 none
显示,然后根据您的比较,它将开始正常工作。
试试这个方法:
if (div.style.display && div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
<强> Fiddle
或者只是将其简化为:
var div,display;
div = document.getElementById('participantsDiv');
display = div.style.display;
div.style.display = (display && display !== 'none') ? 'none' : 'block';
在上面的示例中,我最初提供了一个 css 类来隐藏 div。删除它并看到相同的行为发生。
关于JavaScript 切换可见性需要单击两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908171/