[英]How to change the style of another element inline using javascript?
I would like to change the style of another inside a html element using javascript.我想使用 javascript 更改 html 元素中另一个元素的样式。
I have used the below code to change the current html element.我使用下面的代码来更改当前的 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>
I would like to change the other element's style inside the p tag using javascript.我想使用 javascript 更改 p 标签内其他元素的样式。
can anyone help?有人可以帮忙吗?
Using CSS you can achieve the same使用 CSS 你可以达到同样的目的
<style>
p:hover + h1 {
background-color : red
}
</style>
This should be what you're after (not my work) - check out the fiddle link ...这应该是你所追求的(不是我的工作) - 查看小提琴链接......
<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>
for example if you want to change the color:例如,如果您想更改颜色:
<script>
document.getElementByTagName("p").style.color = "blue";
</script>
that should probably bound to an event, accordingly to what you want to do这可能应该绑定到一个事件,根据你想要做什么
You can easily achieve it with jQuery:您可以使用 jQuery 轻松实现它:
$(function() {
$('#a-element').hover(function() {
$('#b-element').css('background-color', 'yellow');
}, function() {
// on mouseout, reset the background colour
$('#b-element').css('background-color', '');
});
});
If #b comes immediately after #a, the simplest solution is in pure css:如果#b 紧跟在#a 之后,最简单的解决方案是在纯 css 中:
#a:hover + #b {
background: #ccc
}
If between #a and #b are other elements, you have to use ~ like this:如果 #a 和 #b 之间是其他元素,则必须像这样使用 ~ :
#a:hover ~ #b {
background: #ccc
}
use this :用这个 :
<!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>
use with Javascript与 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>
use with css与 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.