解决iframe中fixed失效的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hejiancsdn/article/details/80495333

1.开始先说几句废话,刚开始是因为公司有一个老项目需要添加一个底部的导航栏,这个导航栏需要一直悬挂在底部,刚开始以为很容易,结果接触那个项目的时候才知道那个项目是iframe里面嵌套iframe,非常恶心。结果就有了这个问题,好了废话不多少了,直接上代码,因为公司的项目代码太杂,所以我自己写了一个案例供大家参考。

1.首先说一下案例效果,我会在a页面中嵌套b页面,让b页面中的导商条固定定位在a页面的底部

2.我先说一下我的实现思路,首先既然fixed失效的话,那我们可以去模拟固定定位。那么具体如何去模拟我们考虑一下固定定位的特性,那就是不随滚动条滚动,那么我可以想到我们可以获取滚动条的垂直高度因为是iframe页面所以我们拿到他父级页面的滚动条高度也就是$(parent.window).scrollTop(),这样的话他就会不随滚动条去滚动。但是他会一直在他父级元素的顶部,那么我们要解决这个问题。这时候我想到了用margin-top,但是margin-top给多少呢,首先我们可以确定的是margin-top肯定不是死值,他一定是动态的,因为如果设置死值的话,一旦窗口大小发生变动就出出现位置发生变化。那么如何去动态的去赋值就是我们要解决的问题,我的办法是拿到他父级页面窗口的高度$(window.parent).height() -174,至于为什么要减去174呢,因为iframe页面上有一个导航条所以要减去导航条的高度。这样就可以动态的去给margin-top赋值,还有最重要的一点是我要要监听浏览器窗口的高度,这时候要用到resize事件,好了代码都在下面,大家可以复制一下放到编辑器中看一下效果。

3.这是a页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="jquery.min.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			.top{
				width: 100%;
				height: 100px;
				background-color: red;
				margin-bottom: 20px;
				
			}
			.main{
				width: 100%;
				
			}
			
		</style>
	</head>
	<body>
		<div class="top"></div>
		<div class="main">
			<iframe src="two.html" width="100%" height="2000px"scrolling="no"></iframe>
			
		</div>
	</body>
</html>

4.这是b页面

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="jquery.min.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			.content {
				width: 100%;
				background: yellow;
				/*position: relative;*/
				/*transform: none*/
			}
			
			.content li {
				width: 100%;
				height: 300px;
			}
			
			.fix {
				width: 100%;
				height: 46px;
				background: black;
				position: fixed;
				bottom: 0;
				text-align: center;
				line-height: 46px;
				color: white;
			}
		</style>
	</head>

	<body>
		<div class="content">
			<ul>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
				<li>asdasdas</li>
			</ul>
			<div class="fix">
asdasd
			</div>

		</div>
		<script type="text/javascript">
			
			scrollFixed()
			$(parent.window).resize(function() {
				scrollFixed()
			})
			function scrollFixed (){
				$(".fix").css({
					top : $(parent.window).scrollTop(),
					marginTop: $(window.parent).height() - 174
				});
				$(parent.window).scroll(function() {
					$(".fix").css({
						top : $(parent.window).scrollTop(),
						marginTop: $(window.parent).height() -174

					});
				});
			}
		</script>
	</body>

</html>

5.效果图



猜你喜欢

转载自blog.csdn.net/hejiancsdn/article/details/80495333