关于jQuery,为什么mouseenter()不起作用<input>?



感谢您先检查我的帖子!

mouseenter()适用于标签 h2,但它不适用于<input>。你能说出我的代码有什么问题吗?

$(document).ready(function() {
  $("h2").mouseenter(function() {
    $(this).css("background-color", "green");
  });
  $("input").mouseenter(function() {
    $(this).css("background-color", "green");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <h2>Select Gaming Time:</h2>
  <form method="post">
    <input type="radio" name="time" value="5">5 Minute (Hard) &nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" name="time" value="8">8 Minutes (Normal) &nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" name="time" value="10">10 Minutes (Easy)
  </form>
</div>

您当前正在尝试将单选按钮的背景变为绿色。不幸的是,这无法做到。但是,您可以将收音机旁边的文本换行到标签中,并将标签的背景变为绿色。

作为额外的好处,您还可以使用 for="" 属性和相应的 id="" 使标签可点击。

此外,这只能使用 css h2:hover, label:hover { background- color: green; } .为您节省大量字节来加载!

A. Wolff的代码从这个jsfiddle复制过来:

$(document).ready(function () {
    $("h2").mouseenter(function () {
        $(this).css("background-color", "green");
    });
    $("label:has(:radio)").mouseenter(function () {
        $(this).css("background-color", "green");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
    
<h2>Select Gaming Time:</h2>
    <form method="post">
        <label for="time_5">
            <input type="radio" name="time" value="5" id="time_5">5 Minute (Hard) &nbsp;&nbsp;&nbsp;&nbsp;</label>
        <label for="time_8">
            <input type="radio" name="time" value="8" id="time_8">8 Minutes (Normal) &nbsp;&nbsp;&nbsp;&nbsp;</label>
        <label for="time_10">
            <input type="radio" name="time" value="10" id="time_10">10 Minutes (Easy)</label>
    </form>
</div>

为了避免您混淆mouseenter不适用于输入类型元素。事实并非如此.它有效.你可以看到 这里 .如上文解答所述,最好对单选按钮旁边的文本进行css更改。

最新更新