简体   繁体   English

将鼠标悬停在另一个div上时更改另一个div背景

[英]Change another div background when hover over another div

Trying to change a div background color when hover over another div. 当鼠标悬停在另一个div上时,尝试更改div背景颜色。 But I can't get it to worked. 但我无法让它发挥作用。 Been seing aroud her now, but can't find a similair question. 现在一直在看她,但找不到类似的问题。

<style type="text/css">
    #main {
        width: 960px;
        height: 600px;
        margin: auto;
        position: relative;
        background: red;
    }

    #trykk {
        width: 100px;
        height: 100px;
        background-color: yellow;
    }

    #trykk:hover #main {
        background-color: green;
    }
</style>

<div id="main">
    <div id="trykk">
    </div>
</div>

Thats the code I've been using. 这就是我一直在使用的代码。 The only problem is that I'm not allowed to use javascript. 唯一的问题是我不允许使用javascript。 So is there any way I can change background color on div #main when I hover over div #trykk? 那么当我将鼠标悬停在div #trykk上时,有什么方法可以改变div #main的背景颜色?

A demo related to Rodik's answer, as he said you cannot change select parent using a child hence you cannot change the style of parent element, but if you want you can change your markup, as you said you cannot use javascript but if you can change the markup than it will go like this 一个与Rodik's答案有关的演示,因为他说你不能改变使用孩子的选择父母因此你不能改变父元素的风格,但如果你想要你可以改变你的标记,正如你所说的你不能使用javascript但是如果你可以改变标记比它会像这样

Demo1 demo1的

HTML HTML

<div id="main">Main</div>
<div id="trykk">Trykk</div>

CSS CSS

#main:hover + #trykk {
    background-color: green;
}

Or if you want to nest your div's as you are doing right now, just change the selector like this 或者,如果您想要像现在一样嵌套div,只需像这样更改选择器

Demo2 DEMO2

HTML HTML

<div id="main">Main
<div id="trykk">Trykk</div>
</div>

CSS CSS

#main:hover > #trykk {
    background-color: green;
}

CSS selection only works one way, from parent to child. 从父级到子级,CSS选择仅以一种方式起作用。

A child's state, hence, cannot affect it's parent's state. 因此,孩子的状态不会影响其父母的状态。

A javascript mouseover event will be needed to implement this type of functionality. 需要javascript鼠标悬停事件来实现此类功能。

with jquery you could do this: 使用jquery你可以这样做:

$(function(){
    $("#trykk").hover(function(){
        $("#main").toggleClass("greenBackground");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM