繁体   English   中英

如何集中精力元素?

[英]How to center focused element?

下面的代码侧重于使用javascript的第二个元素,但是焦点元素粘在页面底部。 我想在页面中心有专注元素如何做到这一点?

 $(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> 

您可以使用JS选择焦点元素,然后将窗口滚动到它:

$('html, body').stop().animate({
    scrollTop: $(element_focused).offset().top
}, 300);

使用一点点数学,您可以计算聚焦元素的中心并更改scrollTop值。

添加margin:0 auto; 左/右边距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> 

如果您希望它始终在屏幕中心水平和垂直,即使使用滚动,您也可以使用fixed位置进行一些计算。 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM