簡體   English   中英

將Click處理程序與CSS同級選擇器結合使用時,IE中出現奇怪的行為

[英]Strange behavior in IE when combining click handler with CSS sibling selector

我正在嘗試設計一個通過單擊按鈕觸發的菜單。 當用戶單擊該按鈕時,將運行一個單擊處理程序,該按鈕將該類添加到該按鈕,使用兄弟選擇器的CSS規則使該菜單可見。 它在我測試的所有瀏覽器中工作正常,除了IE 7和8。

在IE 7和8中,我遇到了這些問題:

  1. 單擊該按鈕切換類,但菜單不會出現或消失,直到我將鼠標移動一點點。
  2. 菜單根本不起作用,除非我有一個CSS:菜單子項的懸停聲明。 無論我在宣言中放什么,或者我放了什么東西都沒關系,但沒有它就會顯示菜單。

誰能告訴我為什么會這樣,我能做些什么呢? 我想在菜單中添加一個單獨的類,但我想知道是否有更簡單的修復或解決方法。 這是我的代碼:

<!DOCTYPE html>
<html><head>
<title>IE selector test</title>
<style type="text/css">
button {
  border: outset 1px #eeeeee;
}
button.active {
  border-style: inset;
}
.menu {
  display: none;
  border: solid 1px #888888;
}
button.active ~ .menu {
  display: block;
}
.menu > :hover {
  /* For some reason, the menu doesn't work at all without this declaration */
}
</style>
</head>
<body>
<button type="button" id="menuButton">Menu</button>
<div class="menu">
  <div>option</div>
</div>
<script>
document.getElementById("menuButton").onclick = function() {
  if (this.className) {
    this.className = "";
  } else {
    this.className = "active";
  }
};
</script>
</body>
</html>

您也可以在http://jsfiddle.net/QKqpn/進行測試。

您可以通過強制頁面重繪來解決它:

document.body.className = document.body.className;

http://jsfiddle.net/uGW4M/

BTW,在你的情況下你可以使用+ (一個直接兄弟)組合器而不是更常見的~ (所有后續的兄弟姐妹):

button.active + .menu {/* ... */}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM