簡體   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