我可以使用img:hover获取另一个元素吗? [英] Can I use img:hover to get another element?

查看:464
本文介绍了我可以使用img:hover获取另一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以可以让这项工作

  #element img:hover #otherelement {...} 

like

  #element:hover #otherelement {...} 

重要的是img保持指定,因为

解决方案

你可以做的是通过以下方式选择下一个元素:



相邻兄弟组合器



匹配 element2 ,它们之前有 element1 ,而他们有相同的父。它们也是 siblings ,但 element2 不必紧挨着 element1

  #element img:hover〜#otherelement 

如果 #otherelement img 是兄弟姐妹, c $ c> #otherelement 放置在 img 之后的某处,当 img 徘徊。



这里是一个示例



<$ p $

< div id =parent>
< img src =http://lorempixel.com/200/200/alt =Sport>
< div class =text>这是一个文本。< / div>
< / div>

CSS:

  #parent {
overflow:hidden;
width:200px;
height:200px;
}

.text {
position:relative;
-webkit-transition:.3s all;
-moz-transition:.3s all;
transition:.3s all;
background-color:rgba(255,255,255,.5);
height:40px;
line-height:40px;
}

#parent img:hover + .text {
top:-40px;
}


So is it possible to make this work

#element img:hover #otherelement {...}

like

#element:hover #otherelement {...}

it's important for img to stay specified, because images are automatic in what I'm making.

解决方案

What you can do is selecting next element(s) by:

Adjacent sibling combinator

element1 + element2 Selects every element2 element that are placed immediately after element1 element(s). They're siblings.

#element img:hover + #otherelement

If the #otherelement is placed right after img, it'll be selected when img is hovered.

Another option is:

General sibling combinator

element1 ~ element2 Matches occurrences of element2 that are preceded by element1 while they have the same parent. They're siblings too, but element2 doesn't have to be immediately preceded by element1.

#element img:hover ~ #otherelement

If #otherelement and img are siblings, and #otherelement is placed somewhere after the img, it'll be selected when img is hovered.

Here is an example

HTML

<div id="parent">
    <img src="http://lorempixel.com/200/200/" alt="Sport">
    <div class="text">This is a text.</div>
</div>

CSS:

#parent {
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.text {
  position: relative;
  -webkit-transition: .3s all;
  -moz-transition: .3s all;
  transition: .3s all;
  background-color: rgba(255,255,255,.5);
  height: 40px;
  line-height: 40px;
}

#parent img:hover + .text {
  top: -40px;
}

这篇关于我可以使用img:hover获取另一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆