【问题标题】:Animating on left doesnt move element左侧动画不移动元素
【发布时间】:2016-05-12 20:07:48
【问题描述】:

悬停时,我想移动顶部图片以显示其下方的图片。 DOM 中的 Left 和 Right 值在变化,但视觉上的图片并没有移动。

$(document).ready(function(){
	var left = $('#left').offset().left;
	var right = $('#right').offset().right;
	$("#left").hover(
		function(){
			$("#right #top").css({right:right}).animate({"right": "+=100px"},"slow");
		
		},
		function(){
			$("#right #top").css({right:right}).animate({"right": "-=100px"},"slow");
		});
	
	$("#right").hover(
		function(){
			$("#left #top").css({left:left}).animate({"left": "-=100px"},"slow");
		
		},
		function(){
			$("#left #top").css({left:left}).animate({"left": "+=100px"},"slow");
		});
});
html,body,#wrapper{
  height: 100%;
  min-height: 100%;
}

#wrapper {
  align-items: center;
  display: flex;
  justify-content: center;
}

#center{
	width: 800px;
	text-align:center;
	position:relative;
}

img{
	width:100%;
	height:auto;
	float:left;
}

#left{
	width:400px;
	float:left;
	position:absolute;
}

#right{
	width:400px;
	float:right;
}

#top{
	z-index:1;
}

#under{
   z-index:-1;
   float: none;
   height: auto;
   left: 0;
   position: absolute;
   width: 400px;
}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" href="css/style1.css">	
		<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
		<script type="text/javascript" src="js/script.js"></script>
	</head>
	<body>
		<div id="wrapper">
			<div id="center">
				<div id="left">
					<img src="http://s32.postimg.org/p5mgljj5x/drums_left.jpg" id="top">
					<img src="http://s32.postimg.org/4vp56ei11/workout_left.jpg" id="under">
				</div>
				<div id="right">
					<img src="http://s32.postimg.org/6ep4p4dz9/drums_right.jpg" id="under">
					<img src="http://s32.postimg.org/mzs5r1fph/workout_right.jpg" id="top">
				</div>
			</div>
		</div>
	</body>
	
	<footer>
	</footer>
</html>
我猜在css中使用位置属性有问题吗?

小提琴看起来像这样:https://jsfiddle.net/bjgydLvo/4/

【问题讨论】:

  • 你可能会更好地尝试使用 CSS 动画来做到这一点
  • 你能指出我正确的方向吗?

标签: jquery html css jquery-animate css-position


【解决方案1】:

对动态图像进行分类并添加以下 CSS

.animate{
  left:0;
  transition:all .2s;
  position:relative;
}

jQuery

$('#center').mouseenter(function(){
    $('.animate').css('left','-100%')
})
$('#center').mouseleave(function(){
    $('.animate').css('left','0')
})

示例 https://jsfiddle.net/8fbohssn/1/

如果您想在滑动图像离开时隐藏它,只需将overflow:hidden; 添加到父容器中

示例 https://jsfiddle.net/8fbohssn/2/

【讨论】:

  • 这解决了我的问题,谢谢!有没有一种简单的方法可以隐藏 div 后面的滑动图像?那么当它滑动时,它会消失在“白色背景”后面?
  • 检查我在原始答案中提供的第二个示例
【解决方案2】:

一个问题是您有多个具有相同 id 的元素。 ID 是唯一标识符 - 您可能希望使用类来代替。

this fiddle 中,我删除了#top 并将under 从ID 更改为class,因为您使用了两次。

动画现在可以工作了。如果这不是您想要的结果,请在下方评论。

【讨论】:

  • 嗨,你的解决方案开始做我想做的事,只是我剩下的代码不好,每次我悬停时它都会开始破坏 DOM,向左添加 100。谢谢你的帮助!
猜你喜欢
  • 2012-07-02
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多