在小输入元素中显示IE :: ms-clear伪元素?(Display IE ::ms-clear pseudo element in small input elements?)

我有几个日期和文本的输入元素。 如果它们的宽度大于94px,则显示“X”:: - ms-clear,但我的一些输入较小。

即使输入元素只有50-60px宽,是否有办法告诉IE显示“X”? 该解决方案应该适用于IE9及更高版本。

I have several input elements for dates and texts. If their width is bigger than 94px the "X" ::-ms-clear is displayed but some of my inputs are smaller.

Is there a way to tell IE to display the "X" even if the input elements are only 50-60px wide? The solution should work for IE9 and higher.

最满意答案

您最好的选择是禁用自定义清除按钮,并提供您自己的。 您可以禁用Internet Explorer和Microsoft Edge中的清除按钮,如下所示:

::-ms-clear { display: none }
 

但是,这不会禁用其他浏览器中的自定义清除按钮,例如Google Chrome。 在Chrome中,您需要定位不同的伪元素:

::-webkit-search-cancel-button {
    -webkit-appearance: none;
}
 

Chrome 和Microsoft Edge都了解上述模式。 对于Internet Explorer,您还需要继续使用早期的::-ms-clear元素。

隐藏这些元素后,我们现在可以提供我们自己的:

<form>
    <input type="search">
    <button class="clear">&#x2715;</button>
</form>
 

然后,我们可以使用事件委托来拦截父级<form>上的.clear上的单击事件:

var form = document.querySelector( "form" );

form.addEventListener( "click", function ( event ) {
    event.preventDefault();
    if ( event.target.className === "clear" ) {
        event.target.previousElementSibling.value = "";
    }
});
 

您可以通过https://jsfiddle.net/jonathansampson/ety8bx93/在线查看最终结果。

Your best option here is to disable the custom clear button, and provide your own. You can disable the clear button in Internet Explorer and Microsoft Edge like this:

::-ms-clear { display: none }
 

This will not, however, disable the custom clear button in other browsers, such as Google Chrome. In Chrome, you'll need to target a different pseudo-element:

::-webkit-search-cancel-button {
    -webkit-appearance: none;
}
 

The above pattern is understood by both Chrome and Microsoft Edge. For Internet Explorer, you will need to continue using the earlier ::-ms-clear element as well.

With these elements hidden, we can now provide our own:

<form>
    <input type="search">
    <button class="clear">&#x2715;</button>
</form>
 

We can then use Event Delegation to intercept click events on .clear at the parent <form>:

var form = document.querySelector( "form" );

form.addEventListener( "click", function ( event ) {
    event.preventDefault();
    if ( event.target.className === "clear" ) {
        event.target.previousElementSibling.value = "";
    }
});
 

You can see the end-result online at https://jsfiddle.net/jonathansampson/ety8bx93/.

更多推荐