[英]How to center focused element?
The code below focuses on second element using javascript however the focused element sticks to bottom of page. 下面的代码侧重于使用javascript的第二个元素,但是焦点元素粘在页面底部。 I want to have focused element in the center of page how to do that?
我想在页面中心有专注元素如何做到这一点?
$(function(){ $("#two").focus(); });
body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div>
You can use JS to select the focused element and then scroll the window to it : 您可以使用JS选择焦点元素,然后将窗口滚动到它:
$('html, body').stop().animate({
scrollTop: $(element_focused).offset().top
}, 300);
With a little math you can calculate the center of the element focused and change the scrollTop
value. 使用一点点数学,您可以计算聚焦元素的中心并更改
scrollTop
值。
Add margin:0 auto;
添加
margin:0 auto;
left/right margins to auto
to center the element horizontally: 左/右边距
auto
将元素水平居中:
$(function(){ $("#two").focus().addClass('getCentered'); });
body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} .getCentered{margin:0 auto;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div>
And if you want it always available in the center of the screen horizontally and vertically even with scroll, you can use fixed
position with some calculations. 如果您希望它始终在屏幕中心水平和垂直,即使使用滚动,您也可以使用
fixed
位置进行一些计算。 check the snippet below center calculation with css: 使用css检查中心计算下面的片段:
$(function(){ $("#two").focus().addClass('getCentered'); });
body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} .getCentered{position:fixed; left:50%; top:50%; margin:-25px 0 0 -30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.