[英]How to roughly center the highlighted element in the browser using JavaScript? Similar to duckduckgo
I implemented this user script (open source under MIT/expat) to enable up/down arrows iteration (using the keyboard arrow keys) like this page - https://duckduckgo.com/?q=javascript&ia=web (try pressing the down arrow key there several times and then up arrow - js has to be whitelisted). 我实现了此用户脚本 (在MIT / expat下为开放源代码)以启用向上/向下箭头迭代(使用键盘的箭头键),类似于此页面-https://duckduckgo.com/?q= javascript &ia =web (尝试按向下键箭头键几次,然后向上箭头-js必须列入白名单)。
However, the viewport is always positioned the top-left of the highlighted/selected/active element. 但是,视口始终位于突出显示/选定/活动元素的左上方。 What is the easiest way to make it more like DDG where the active item does not always scroll the page and is roughly at the centre?
使它更像DDG的最简单方法是什么?在DDG中,活动项并不总是滚动页面并且大致位于中心?
Both jQuery or Vanilla JS are OK. jQuery或Vanilla JS都可以。
Note: the script is available for installation here for now and is readable and useful in the context of metacpan searches such as https://metacpan.org/search?q=config . 注意:该脚本现在可以在此处安装,并且在metacpan搜索(例如https://metacpan.org/search?q=config)的上下文中可读且有用。 See https://userscripts-mirror.org/ .
参见https://userscripts-mirror.org/ 。
Sample of calculation for a vertical-centered position: 垂直居中位置的计算示例:
elt top position - elt height/2 - container height/2
顶部高度-高度2-容器高度/ 2
Regarding your script, try to replace: 关于您的脚本,请尝试替换:
window.scrollTo( el.offset().left , el.offset().top );
By: 通过:
window.scrollTo( el.offset().left , el.offset().top - el.innerHeight()/2 - window.innerHeight/2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.