带绝对定位的输入标签悬停问题

时间:2015-09-08 15:46:57

标签: html css css-selectors hover pseudo-class

<input type="text"/>上有:hover和样式,例如:

input:hover {
    border-color: red;
}

我想在我的输入中添加搜索图标。当我将鼠标悬停在图标上时,输入:hover样式很适用,请尝试:

JSFiddle

input, span {
    display: inline-block;
    vertical-align: middle;
    height: 30px;
}

input:hover {
    border-color: red;
}

span {
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-128.png) 50% 50%/100% 100% no-repeat;
    width: 25px;
    height: 25px;
}
<label>
    <input type="text"/>
    <span></span>
</label>

但如果我在输入上直观地显示搜索图标,则当我将鼠标悬停在图标上时输入:hover样式不适用:

JSFiddle

label {
    position: relative;
}

input, span {
    display: inline-block;
    vertical-align: middle;
    height: 30px;
}

input:hover {
    border-color: red;
}

span {
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-128.png) 50% 50%/100% 100% no-repeat;
    width: 25px;
    height: 25px;
    position: absolute;
    top: -4px;
    right: 4px;
}
<label>
    <input type="text"/>
    <span></span>
</label>

问题:我可以修复此行为吗?当我在任何时候悬停输入时,我想应用输入:hover样式。

PS 我知道我可以在:hover上设置<label>个样式或者使用Javascript / jQuery设置它,但我不想这样做,因为我有很多案例使用<input>和其他情况下我没有<label>和图标,只有<input>。我想要没有它的解决方案。

2 个答案:

答案 0 :(得分:1)

一种解决方案是添加poiter-events规则:

span {
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-128.png) 50% 50%/100% 100% no-repeat;
    width: 25px;
    height: 25px;
    position: absolute;
    top: -4px;
    right: 4px;
    pointer-events: none; <!-- this line -->
}

演示:http://jsfiddle.net/kfgggd1b/4/

但它得不到很好的支持:http://caniuse.com/#search=pointer

另一种方法是通过在输入之前放置span然后

来重新组织HTML
span:hover + input, 
input:hover {
    border-color: red;
}
span {
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-128.png) 50% 50%/100% 100% no-repeat;
    width: 25px;
    height: 25px;
    position: absolute;
    top: -4px;
    right: 4px;
}

演示:http://jsfiddle.net/kfgggd1b/5/

答案 1 :(得分:1)

您可以在输入中添加透明背景,并在其下方放置图标(使用较少的z-index)。

    * {
        box-sizing: border-box;
    }
    label {
        position: relative;
        display: inline-block;
        background: white;
    }
    input {
        width: 100%;
        border: 1px solid #000;
        height: 30px;
        outline: none;
        position: relative;
        z-index: 2;
        background: transparent;
    }
    input:hover {
        border-color: red;
    }
    span {
        background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-128.png) 50% 50%/100% 100% no-repeat;
        width: 25px;
        height: 25px;
        margin-top: -13px;
        position: absolute;
        top: 50%;
        right: 4px;
        z-index: 1;
    }

这是Fiddle

相关问题