如何将js函数添加到仅在前面的元素处于焦点上时显示的元素

时间:2014-07-22 03:22:15

标签: javascript jquery html css frontend

这是一个演示:http://jsfiddle.net/t9aAf/

任务是单击菜单中的项目,以便使用所选值填充输入字段。 但它不起作用。

HTML:

<div class="wrapper">

  <input type="text">

  <div class="hints-menu">
    <span class="hints-title"><span>Title 1</span></span>
    <span class="hint" title="Some title">Item 1</span>
    <span class="hint" title="Some title">Item 2</span>
    <span class="hint" title="Some title">Item 3</span>
    <span class="hints-title"><span>Title 2</span></span>
    <span class="hint" title="Some title">Item 4</span>
    <span class="hint" title="Some title">Item 5</span>
    <span class="hints-title"><span>Title 3</span></span>
    <span class="hint" title="Some title">Item 6</span>
    <span class="hint" title="Some title">Item 7</span>
    <span class="hint" title="Some title">Item 8</span>
    <span class="hint" title="Some title">Item 9</span>
  </div>

</div>

的CSS:

.wrapper {
    width: 260px;
    margin: 30px auto;
}
input {
    width: 252px;
    height: 28px;
    padding: 0 4px;
    line-height: 20px;
    border: 1px solid #ddd;

    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
}
input:focus {
    outline: none;
}
input:focus + .hints-menu {
    display: block;
}
.hints-menu {
    background: #fff;
    position: relative;
    display: none;
    width: 240px;
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #ddd;

    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
}
.hints-menu:before,
.hints-menu:after {
     bottom: 100%;
     left: 83%;
     border: solid transparent;
     content: "";
     height: 0;
     width: 0;
     position: absolute;
     pointer-events: none;
}
.hints-menu:before {
     border-color: transparent;
     border-bottom-color: #ddd;
     border-width: 9px;
     margin-left: -9px;
}
.hints-menu:after {
     border-color: transparent;
     border-bottom-color: #fff;
     border-width: 8px;
     margin-left: -8px;
}
.hints-title,
.hint {
    display: block;
    width: 100%;
    height: 22px;
    line-height: 22px;
    color: #555;
}
.hints-title {
    position: relative;
    margin: 0 0 15px;
    text-align: center;
    font-size: 15px;
    border-bottom: 1px solid #555;
}
.hints-title span {
    background: #fff;
    position: absolute;
    top: 50%;
    right: 10%;
    padding: 0 5px;
}
.hint {
    font-size: 14px;
    cursor: pointer;
}
.hint:hover {
    color: #6fa024;
}

JS:

$(document).on("click",".hint",function(){
            alert("haha");
            alert($(this).val());
});

因为我还不熟悉编码。非常感谢帮我修复错误! 谢谢你!

2 个答案:

答案 0 :(得分:2)

将以下声明添加到您的代码中:http://jsfiddle.net/UL9q9/。即使输入已丢失,它也会阻止菜单被隐藏时隐藏菜单:焦点。

input:not(:focus) + .hints-menu:hover {
    display: block;
}

答案 1 :(得分:1)

似乎这里发生的事情是您在输入字段具有焦点时设置了显示的菜单,但是尝试单击该字段会失去焦点并隐藏菜单。