2016-05-12 51 views
1

我是网络开发新手,因此我正在参加由Shawn Wildermuth主持的Pluralsight课程,名为“用ASP.NET Core RC1,MVC 6,EF7 & AngularJS构建Web应用程序”。在他的jQuery的模块,余文乐有这样的一段代码,完美的作品是为他面向鼠标事件的问题

 var main = $("#main"); 
    main.on("mouseenter", function() { 
     main.style = "background-color: #888;"; 
    }); 
    main.on("mouseleave", function() { 
     main.style = ""; 
    }); 

我有我的id的index.html页=“main”的一个div,js文件中引用,其他的jQuery功能在相同的文件工作,我只是不能让这段代码工作。我知道这不重要,但在这一点上它是个人的。任何建议都有帮助。谢谢!

回答

2

您不能像这样访问样式属性。请尝试以下操作:

var main = $("#main"); 

main.mouseenter(function() { 
    main.css("background-color", "#888"); 
}); 
main.mouseleave(function() { 
    main.css("background-color", "none"); 
}); 
+0

我编辑它。再试一次。虽然它应该也是第一次。 – webbul

+0

它的工作!谢谢。 –

3

由于style是本地DOM元素的属性,main是一个jQuery对象。您可以使用.css().removeAttr() jQuery方法来获得所需的结果。

var main = $("#main"); 
main.on("mouseenter", function() { 
    main.css("background-color": "#888"); 
}); 
main.on("mouseleave", function() { 
    main.removeAttr('style'); 
}); 
1

试试这个:

var main = document.getElementById("main"); 

    main.onmouseenter=function(){ 
     main.setAttribute('style', 'background-color:#888;'); 
    }; 
    main.onmouseleave=function(){ 
     main.removeAttribute("style") 
    };