用鼠标点击或鼠标悬停显示和隐藏内容

时间:2015-07-10 04:52:09

标签: jquery html css

我有一个按钮并将其放在浏览器的顶部。因此,当鼠标单击或鼠标悬停在此定位按钮上时,我需要显示下拉列表。

HTML

  <div class="translator">
    <div class="translate-btn">Translator</div>
    <div class="translate-dropdown">
      <select>
        <option>Translate-1</option>
        <option>Translate-2</option>
        <option>Translate-3</option>
      </select>
    </div>
  </div>

CSS

.translator {
    position: absolute;
    top: 0;
    right: 10%;
    z-index: 9999;
}

.translate-btn {
  background-color: rgba(136, 121, 91, 0.8);
  border-radius: 0 0 5px 5px;
  color: #fff;
  cursor: pointer;
  font-size: 13px;
  font-weight: bold;
  padding: 4px 15px 5px;
  text-align: center;
  text-transform: uppercase;
}

使用此HTML我需要在用户点击或鼠标悬停在“translate-btn”时显示“translate-dropdown”DIV。

任何人都可以告诉我是否可以使用纯CSS或者我是否需要使用jquery?

希望有人可以帮助我。 谢谢。

2 个答案:

答案 0 :(得分:5)

仅使用CSS:

.translate-dropdown {
    display: none;
}

.translator:hover .translate-dropdown {
    display: block;
}

完整的工作示例:

.translator {
  position: absolute;
  top: 0;
  right: 10%;
  z-index: 9999;
}

.translate-btn {
  background-color: rgba(136, 121, 91, 0.8);
  border-radius: 0 0 5px 5px;
  color: #fff;
  cursor: pointer;
  font-size: 13px;
  font-weight: bold;
  padding: 4px 15px 5px;
  text-align: center;
  text-transform: uppercase;  
}

.translate-dropdown {
    display: none;
}

.translator:hover .translate-dropdown {
    display: block;
}
  <div class="translator">
    <div class="translate-btn">Translator</div>
    <div class="translate-dropdown">
      <select>
        <option>Translate-1</option>
        <option>Translate-2</option>
        <option>Translate-3</option>
      </select>
    </div>
  </div>

答案 1 :(得分:1)

纯CSS对此类任务有限制。这是一个使用jQuery的javascript方法(因为我不是CSS开发人员):

$(document).ready(function() {
        var $target = $('.translate-dropdown');
        $('div.translate-btn').on({ 
                    mouseenter: function(e){
                        $target.css('visibility', 'hidden');     
                    },
                    mouseleave:function(e){
                        $target.css('visibility', 'visible');  
                    },
                   click:function(e){

                   $target.css('visibility', 'visible');
// here you can toggle a class name to track the state of the div and based on the state hide or show it. 

                    }
                });
        }

您可以使用jQuery .hide().show()代替.css(),但这些会设置CSS display: none,这并不总是隐藏元素的目标。