Javascript:更改<h2>标题的颜色为mouseover()

Javascript: Change <h2> headings color onmouseover()

本文关键字:颜色 mouseover gt 更改 lt h2 Javascript 标题      更新时间:2023-09-26

我正在尝试实现一些本地Javascript代码,这样当您将鼠标悬停在标题上时,标题就会改变颜色。

我会把所有JS代码和HTML放在底部,这样你就可以在上下文中看到它,但我添加到.JS文件中的代码如下:

//change <h2> on mouseover/mouseout
document.getElementsByClassName("heading2").onmouseover.style.color="red";

HTML文档:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Session 5 - Dynamic Menu</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script src="dynamicmenu.js"></script>
</head>
<body>
<h1>Web Programming Languages</h1>
<h2>JavaScript</h2>
<p>
    JavaScript (JS) is an interpreted computer programming language. As part of web browsers, implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content 
</p>
<h2>PHP</h2>
<p>
    PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. PHP is now installed on more than 244 million websites and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1995, the 
</p>
<h2>Ruby</h2>
<p>
    Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.Ruby embodies syntax inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp. It supports multiple programming paradigms, includin
</p>
<h2>ASP</h2>
<p>
    Active Server Pages (ASP), also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically generated web pages. Initially released as an add-on to Internet Information Services (IIS) via the Windows NT 4.0 Option Pack (ca. 1996), it was subsequently included as a free 
</p>
<h2>Java Server Pages</h2>
<p>
    Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime; each JSP's servlet is cached and re-used until the original JSP is modified.
</p>
</body>
</html>

Javascript代码:

 //function to create dynamic menu...
    function dynamicMenu() {
        //Get all <h2> headings in to a container
        var headings = document.getElementsByTagName("h2");
        //Create <div> for menu
        var menu = document.createElement("div");
        //Set id attribute for <div>
        menu.setAttribute("id", "navWrap")
        //Create <ul> for menu list items
        var menuUL = document.createElement("ul");
        //Set id attribute for <ul>
        menuUL.setAttribute("id", "mainNav");
        //Append the <ul> to the <div> as a child
        menu.appendChild(menuUL);
        //Set up loop to populate menu
        for (var i = 0; i < headings.length; i++) {
            //Collect the text content of h2 headings
            var linkText = headings[i].childNodes[0].nodeValue;
            //Create <li> element
            var menuULitem = document.createElement("li");
            //Append <li> to <ul> as child
            menuUL.appendChild(menuULitem);
            //Create <a> tag element
            menuAtag = document.createElement("a");
            //Append <a> to <li> as child
            menuULitem.appendChild(menuAtag);
            //Set the <a> href attribute to point to the anchor tag in body of document
            menuAtag.setAttribute("href", "#item" + i)
            //Append link text as a hchild of <a>
            var menuText = document.createTextNode(linkText);
            menuAtag.appendChild(menuText);
            //Create an anchor point for each <h2>
            var anchor = document.createElement("a");
            //Set anchor attribute name
            anchor.setAttribute("name", "item" + i);
            //Insert anchor in to DOM
            document.body.insertBefore(anchor, headings[i]);
            //Give headings a class attribute
            headings[i].setAttribute("class", "heading2");
        }
        //Insert the Menu created in above loop in to the DOM
        document.body.insertBefore(menu, document.body.firstChild);
        //change <h2> on mouseover/mouseout
        document.getElementsByClassName("heading2").onmouseover.style.color="red";

    }//close function (dynamicMenu)
window.onload = dynamicMenu;

使用CSS

h2:hover
{
    color : red;
}

如果鼠标移出时不需要删除颜色,请使用

var headers = document.getElementsByTagName("h2");
for (var i in headers)
{
    headers[i].onmouseover = function()
    {
        this.style.color = 'red';
    }
}

你可以这样做:

<h2 id="heading2" onmouseover="myFunction()">The Heading</h2>
<script>
function myFunction() {
   document.getElementById("heading2").style.color = "red";
};
</script>

或者你可以这样做:

<h2 onmouseover="this.style.color = 'red'">The Heading</h2> 

使用jquery不是更容易吗。您可以执行以下操作:$("h2").hover(function() { $("h2").css(color:"red); });

在函数末尾使用本机javascript:

var tags = document.getElementsByClassName("heading2");
// For each tag we add an event listener
for (var i=0;i<tags.length;i++){
    tags[i].onmouseover = mouseIn;
    tags[i].onmouseout = mouseOut;
}
function mouseIn (element) {
    element.target.style.color = "red";
}
function mouseOut (element) {
    element.target.style.color = "inherit";
}

更好(使用jquery(,将其添加到<head>标签:

<script src="http://code.jquery.com/jquery-latest.js"></script>

所以在你的页面底部或其他.js:

// Add event with event delegation 
// (does not care about add new .heading2 elements 
// and only an event is asigned to 'body' tag
$('body').on('mouseover', '.heading2' ,function(){ $(this).css({"color":"red"}); });
$('body').on('mouseout', '.heading2' ,function(){ $(this).css({"color":"inherit"}); });

更好更简单!(最简单的css(:

在.css样式中:

.heading2:hover {
    color: 'red';
}

您当前的语法不是有效的Javascript代码。

您试图实现的目标可以使用以下Javascript语法选项之一来完成:

// Option 1: Event Listener
document.getElementsByClassName("heading2")[0].addEventListener("mouseover",
    function() { 
        this.style.color = "red";
    }, true);

// Option 2: Element Method
document.getElementsByClassName("heading2")[0].onmouseover = function() { 
    this.style.color = "red";
}; 

// Option 3: HTML Activation
<script>
    function setColor() { 
        this.style.color = "red";
    }
</script>
<h2 class="heading2" onmouseover="setColor()"></h2>

当然,您也可以使用更简单的CSS选项:

h2.heading2:hover {
    color: red; 
}

或者像JQuery这样的Javascript库。