Javascript:在屏幕中间显示元素dons'不要在固定的岗位上工作
Javascript: show the element in the middle of screen doesn't work with fixed postion
当点击按钮时,我需要元素垂直地位于屏幕的中间,无论浏览器的高度如何调整,它总是在中间。
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="button">click me</button>
<div id="element">balah</div>
</html>
<style>
#element{
position: fixed;
color: red;
}
</style>
我试过了:
<script>
$("#button").click(function(){
$('#element').css('margin-top',$(window).innerHeight()/2);
})
</script>
不需要使用JS,这可以用纯CSS完成;
.fixed {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
您也需要考虑元素来计算屏幕上的位置。。。
function FixDivCtrl() {
var btn = $('#test');
var target = $('#element');
btn.click(function() {
var coords = {
"margin-top": target.height() / -2,
"margin-left": target.width() / -2,
"position": "fixed",
"left": "50%",
"top" : "50%"
};
target.css(coords);
});
}
jQuery(document).ready(FixDivCtrl);
div {
background-color: red;
width: 50px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Make it Fixed</button>
<div id="element"></div>
创建一个cuss类,其中Top、l、r、b设置为0px,margin:auto和position fixed。
尚未测试,但您可以使用addClass和removeClass来添加新的cuss类。
例如:$(您的元素(.addClass("center"(;
div.center {
background-color: red;
width: 50px;
height: 50px;
Top:0px;
left:0px;
right:0px;
Bottom:0px;
Position:fixed;
Margin:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Make it Fixed</button>
<div id="element"></div>
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 如何在HTML / CSS中填充垂直和滚动中间窗格(Chrome可以工作,但不能Firefox)
- 键入js不在中间人中工作
- 自定义掩码函数不工作时,插入字符在中间Javascript/JQuery
- 为什么这段代码作为中间件而不是作为函数工作得很好?
- react redux中间件的流程是如何工作的
- 为什么http-auth不能与express一起工作.静态的中间件
- express服务器如何与wepback中间件协同工作以实现热重新加载
- 中间件的分派、下一步和排序在react redux中是如何工作的
- 谷歌地图setCenter使用标记不能正常工作,因为它显示市场在左上角而不是中间
- Javascript:在屏幕中间显示元素dons'不要在固定的岗位上工作