简体   繁体   English

如何使用JavaScript在浏览器中大致居中显示突出显示的元素? 类似于duckduckgo

[英]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.

相关问题 如何选择DuckDuckGo元素。 AJAX - How to Select DuckDuckGo Element. AJAX 使用javascript转换元素内突出显示的文本 - Transforming highlighted text inside an element using javascript 如何使用php / javascript从用户浏览器中获取突出显示/选择的数据? - how to get highlighted/selection data from a users browser using php/javascript? 为什么 DuckDuckGo 搜索结果在浏览器上与使用请求时不同? - Why are DuckDuckGo search results different on the browser vs. using request? 如何从具有类似类的 HTML 获取某些元素(使用 JavaScript)? - How to get certain element (using JavaScript) from HTML with similar classes? 使用Javascript,如何缩放相对于视口中心的元素? - Using Javascript, how can I scale an element relative to the center of a viewport? 如何使用 javascript 找到二维数组的中心元素的索引? - How to find the index of the center element of a 2d array using javascript? 如何使用JavaScript验证标签或元素在网页上是否居中对齐 - How to verify if a label or element is center aligned on web page using javascript 使用javascript将元素定位在svg视图框的中心 - Position element at center of svg viewbox using javascript 如何大致确定JavaScript或CSS中设备的物理尺寸? - How can I roughly determine the physical size of a device in javascript or css?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM