jquery - 使用 .on() Jquery 函数

标签 jquery html css

我知道这段代码是错误的。我要全部<p>获得颜色的元素 cornflowerblue当我将鼠标放在我网页中的一个段落上时,在我的 HTML 中。 我用其他方法做了同样的事情,但我怎么能用 on() 来做呢? ?

jQuery:我知道还有其他方法可以做到这一点,但我想试试这个,使用 on() .我为该函数命名,但我很确定这不正确。

ChangeColorOnHover("p")
$(document).ready(function ChangeColorOnHover(elementtype) {
    $element = $(elementtype)
    $element
    .on({
        mouseenter: function (event) {
            var $this = $(this)
            $this.addClass(".IsHover")
        }
    })
    .on({
        mouseleave: function () {
            var $this = $(this)
            $this.removeClass(".IsHover")
        }
    })
})

CSS:

.container {
    font-family: sans-serif;
    font-weight: 100;
    max-width: 960px;
    margin: 20px auto;
}
p {
    color: tomato;
    margin-top: 2em;
}
p.IsHover{
    color:cornflowerblue;
}

HTML:(csstestview 是外部 CSS 文件的名称)。 HTML 正在识别该 CSS 文件,我已经对此进行了探测。

@Styles.Render("~/bundles/csstestview")  
<div id="firstdiv" class="divvv">
  <img src="/images/Soccer.jpg" width="60" height="60" alt="soccer icon" />
  <p id="pp" class="pa"> this is a <em>paragraph</em></p>
  <p>paragraph testing</p>
</div>

最佳答案

$(function () {
    var ChangeColorOnHover = function(elementtype) {
        //Select all elements
        $element = $(elementtype);
        //Set up event handlers
        $element.on('mouseenter', function() {
            //No need for . when adding a class
            $(this).addClass("IsHover");
        });
        $element.on('mouseleave', function() {
            //No need for . when removing a class
            $(this).removeClass("IsHover");
        });
    };

    //Call your function
    ChangeColorOnHover("p");

});

关于jquery - 使用 .on() Jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632098/

相关文章:

jquery - Superfish 插件 : $. fn.extend({...}) -- 这段代码是如何工作的?

javascript - 无法使用ajax添加评论

html - 修改下拉菜单的外观

html - 使用严格的 DOM 结构设计标签小部件

javascript - 自动完成 - 自定义渲染项目/菜单和项目选择问题

javascript - 如何使用YUI在select标签中制作真正的鼠标点击事件?

html - 跨浏览器解决方案 : Have links clickable when under image

html - CSS3 : If input checked, 获取输入数据属性作为 :before of "p"sibling

html - 使绝对div的内容可滚动

html - 边界半径在 Angular 落处中断