CSS attr属性选择器实现列表过滤效果实例页面

回到相关文章 »

代码:

CSS代码:
.search {
    width: 180px;
    padding: 5px;
    -webkit-box-sizing: content-box;
}
.datalist {
    display: block;   
    width: 190px;
    background-color: #fff;
    box-shadow: 0 1px #ccc, 1px 0 #ccc, -1px 0 #ccc, 0 -1px #ccc;
    overflow: hidden;
    visibility: hidden;
}
.search:focus + .datalist {
    visibility: visible;
}
...
                
HTML代码:
<input type="search" class="search" id="city" placeholder="输入省会或直辖市名称" />
<label class="datalist" for="city"> 
    <div class="list" data-index="重庆市chongqing">重庆市</div>
    <div class="list" data-index="哈尔滨市haerbing">哈尔滨市</div>
    <div class="list" data-index="长春市changchun">长春市</div>
    ...
</label>
                
JS代码:
var eleStyle = document.createElement("style"),
    eleInput = document.querySelector("#city");
    
// 用来CSS控制的style插入
document.querySelector("head").appendChild(eleStyle);

// 文本框输入
eleInput.addEventListener("input", function() {
    var val = this.value.trim().toLowerCase();
    if (val !== '') {
        eleStyle.innerHTML = '.list:not([data-index*="'+ this.value +'"]) { display: none; }';
    } else {
        eleStyle.innerHTML = '';
    }
});
                

效果: