在 Javascript 中下划线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13109967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:50:19  来源:igfitidea点击:

Underlining in Javascript?

javascriptcsspseudo-class

提问by Code Monkey

Upon the realization that you can't have an inline pseudoclass -- How to write a:hover in inline CSS?-- I looked into having Javascript do the same job with the onMouseOverand onMouseOutevents to simulate the :hoverpseudoclass. I'm trying to remove the underline from the text when the mouse is above it. Is there a snippet of Javascript someone can offer that can do that?

意识到您不能拥有内联伪类后——如何在内联 CSS 中编写 a:hover?-- 我研究让 Javascript 对onMouseOveronMouseOut事件做同样的工作来模拟:hover伪类。当鼠标位于文本上方时,我试图从文本中删除下划线。有人可以提供可以做到这一点的Javascript片段吗?

I tried onMouseOver="this.style.textDecoration="none"", but I think the contrasting quotations are throwing everything off.

我试过了onMouseOver="this.style.textDecoration="none"",但我认为对比鲜明的引语把一切都抛在了脑后。

Any ideas?

有任何想法吗?

Note: unfortunately, this effect must be achieved without the use of an external or internal stylesheet (inline only).

注意:不幸的是,这种效果必须在不使用外部或内部样式表(仅限内联)的情况下实现。

回答by NullPoiиteя

you can do this by

你可以这样做

 onMouseOver="this.style.textDecoration='none';"

回答by bukart

Here's your answer:

这是你的答案:

<a onmouseover="this.style.textDecoration='none';"  onmouseout="this.style.textDecoration='underline';">hover me</a>


if you're able to use jQuery it would be easier. Just write once the following code. You haven't to change your markup then.


如果您能够使用 jQuery,那就更容易了。只需编写一次以下代码。那么您不必更改标记。

<script type="text/javascript">
(function($) {
    $( function() {
        $('a').hover(
            function() {
                $(this).css('text-decoration','none');
            },
            function() {
                $(this).css('text-decoration','underline');
            }
        )
    } );
} (jQuery));
</script>

回答by Oriol

I think you shouldn't use javascript, but CSS:

我认为你不应该使用 javascript,而是使用 CSS:

.underlineHover:hover {
    text-decoration: underline;
}
<span class="underlineHover">Content</span>

Note: I used the class underlineHover, but be aware that classes should have a semantic meaning instead of styling one.

注意:我使用了 class underlineHover,但请注意, classes 应该具有语义而不是样式。