jquery - 使 DIV 和 UL 像 SELECT 元素一样

标签 jquery html css

我想做的是替换 <span class="hideSelect"> 的“我的下拉列表”文本带有被点击文本的元素 <li> , 为了让它像 <select> 一样工作元素。

CSS:

.myDrop {
  border: 1px solid #ddd;
  border-radius: 3px;
  padding: 5px 10px;
  max- width: 100%;
  min-width: 100%;
  vertical-align: middle;
}

.mydrop ul {
  display: none;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 3px;
  max-height: 250px;
  overflow: auto;
}

.mydrop ul li {
  padding: 5px 10px;
}

.mydrop ul li:hover {
  background: #ddd;
}

JavaScript:

$(".mydrop").click(function(e) {
    e.stopPropagation();
    $(".mydrop>ul").stop().slideToggle(500);
    $(document).click(function(){
      $(".mydrop>ul").hide();
    });
  });
  $(".mydrop>ul li").click(function () {
    $(".hideSelect").hide();
  });

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-3">
      <div class="mydrop">
        <div class="myDrop">
          <span class="hideSelect">
              <span id="caption">my dropdown</span>
              <span class="pull-right"><i class="fa fa-caret-down"></i>
    </span>
          </span>
        </div>
        <ul id="options">
          <li class="visilkl">Hot Dog, Fries and a Soda</li>
          <li>Burger, Shake and a Smile</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
          <li>Sugar, Spice and all things nice</li>
        </ul>
      </div>
    </div>
  </div>
</div>

最佳答案

如果我没理解错你想隐藏 <span class="hideSelect"> 的内容所以 my dropdown 一旦<ul>中选择了一个值,将被隐藏.

你可以这样实现:

$(".mydrop").click(function(e) {
    e.stopPropagation();
    $(".mydrop>ul").stop().slideToggle(500);
    $(document).click(function() {
      $(".mydrop>ul").hide();
    });
});
$(".mydrop>ul li").click(function() {
    $(".hideSelect").text(this.innerHTML); //Get the text from the clicked li and write it to the span with class hideSelect
})

HTML 没有改变

有关演示,请参阅此 JSFiddle

希望这对您有所帮助!

关于jquery - 使 DIV 和 UL 像 SELECT 元素一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45635038/

相关文章:

html - 使用媒体查询修复移动设备的 div 位置

Jquery 轮播和 JQuery UI slider

javascript - 如何在本地文件夹上调用json

带有复选框的 jQuery 版本控制错误

javascript - 将鼠标悬停在一个 div 上时更改其他 div 的类

javascript - 更改标签内的文本 onclick

Safari 中的 CSS 全宽背景图像(负边距)

jquery - Angular2菜单多级下拉菜单不起作用

php - 日期选择器如何选择从下拉列表中选择的月份

css - 转换 Firefox 中的错误?