用javaScript 写一个类似Andriod TV focus 方法。已知div在页面中的offsetTop,offsetLeft,得到每个div的上下左右键对应的div.…
- User
用javaScript 写一个类似Andriod TV focus 方法。已知div在页面中的offsetTop,offsetLeft,得到每个div的上下左右键对应的div. div的获得用document.querySelectorAll( ".src-pages-special-index-module__list--1mCGP" ),是个数组
- Assistant
- User
- Assistant
看起来你的代码基本上是正确的,但是在选择器中有一个小缺陷。在HTML中,
class属性中包含“-”字符的类必须加引号。要解决此问题,只需在选择器中将“–”字符替换为“-”,如下所示:const elements = document.querySelectorAll(".src-pages-special-index-module__list-1mCGP");并在HTML中做相应调整:
<div class="src-pages-special-index-module__list-1mCGP"></div>这样应该就能正常使用焦点控制了。
- User
有个问题,是按上下键,没有对应起来,不是垂直向下,而且向下到下一行的第一个,请优化
- Assistant
- User
上下键有问题,左右键是正确的,请优化
- Assistant
感谢指出问题。上下键的问题出在
getFocusableElements函数中。我们需要修改一下计算上下元素的方式。以下是修改后的代码:
function getFocusableElements(elem) { const rect = elem.getBoundingClientRect(); const top = rect.top + window.pageYOffset - document.documentElement.clientTop; const left = rect.left + window.pageXOffset - document.documentElement.clientLeft; let firstRowIndex = -1; let lastRowIndex = -1; rowIndices.forEach((indices, i) => { if (indices.indexOf(currentIndex) !== -1) { firstRowIndex = i; lastRowIndex = firstRowIndex + Math.floor((indices.length - 1) / 4) } }); const focusableElements = { up: undefined, down: undefined, left: undefined, right: undefined }; elements.forEach((el, i) => { if (i !== currentIndex) { const elRect = el.getBoundingClientRect(); const elTop = elRect.top + window.pageYOffset - document.documentElement.clientTop; const elLeft = elRect.left + window.pageXOffset - document.documentElement.clientLeft; if (elTop === top) { if (elLeft + elRect.width < left && (!focusableElements.left