簡體   English   中英

如何使用 javascript 內聯更改另一個元素的樣式?

[英]How to change the style of another element inline using javascript?

我想使用 javascript 更改 html 元素中另一個元素的樣式。

我使用下面的代碼來更改當前的 html 元素。

<p onmouseover="this.style.color = 'black;">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>

我想使用 javascript 更改 p 標簽內其他元素的樣式。

有人可以幫忙嗎?

使用 CSS 你可以達到同樣的目的

<style>
 p:hover + h1 {
  background-color : red
 }
</style>

這應該是你所追求的(不是我的工作) - 查看小提琴鏈接......

<html>
<body>
    <span id="div1" style="color:black;" onmouseover="stext()" onmouseout="htext()">TEXT1</span><p />
    <hr color="black" />
<span id="div2" style="color:red;" onmouseover="htext()" onmouseout="stext()">Text2</span> 

</body>

http://jsfiddle.net/FFCFy/16/

例如,如果您想更改顏色:

<script>
document.getElementByTagName("p").style.color = "blue";
</script>

這可能應該綁定到一個事件,根據你想要做什么

您可以使用 jQuery 輕松實現它:

$(function() {
  $('#a-element').hover(function() {
    $('#b-element').css('background-color', 'yellow');
  }, function() {
    // on mouseout, reset the background colour
    $('#b-element').css('background-color', '');
  });
});

如果#b 緊跟在#a 之后,最簡單的解決方案是在純 css 中:

#a:hover + #b {
    background: #ccc
}

如果 #a 和 #b 之間是其他元素,則必須像這樣使用 ~ :

#a:hover ~ #b {
    background: #ccc
}

用這個 :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <p style="color:red;" onmouseover="ch(event)">This text should be changed</p>
    <h1>How to change this element when hovered on p element</h1>

    <script>
        function ch(e) {
            e.target.style.color = "black";
            alert();
        }
    </script>

</body>
</html>

與 Javascript 一起使用

 function change(that){ document.getElementsByTagName('h1')[0].style.color="red"; }
 <p onmouseover="change()">This text should be changed</p> <h1>How to change this element when hovered on p element</h1>

與 css 一起使用

 p:hover + h1{ color:red; }
 <p >This text should be changed</p> <h1>How to change this element when hovered on p element</h1>

jQuery("p").mouseover(function(){
   jQuery("h1").css("color", "yellow");
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM