在标签索引中关注下一个元素


103

我试图根据具有焦点的当前元素将焦点移至选项卡序列中的下一个元素。到目前为止,我还没有找到任何搜索结果。

function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn 

    currentElementId = "";
    currentElement.nextElementByTabIndex.focus();
}

当然,nextElementByTabIndex是这项工作的关键部分。如何在标签序列中找到下一个元素?该解决方案将需要基于JScript,而不是基于JQuery。


3
你为什么有这条线currentElementId = "";

1
我认为任何浏览器都不会公开制表符顺序信息-浏览器本身使用的算法太复杂而无法复制。也许您可以限制自己的要求,例如“仅考虑inputbutton以及textarea标记和忽略tabindex属性”。
弗拉基米尔·帕兰特

我们需要查看您的.newElementByTabIndex代码,因为那是行不通的。
0x499602D2 2011年

2
再说一遍,也许对特定标签的限制是不必要的-可以检查该focus()方法是否存在。
弗拉基米尔·帕兰特

1
@David那是不存在的功能,因此是我的问题。:D
JadziaMD 2011年

Answers:


23

没有jquery:首先,在您的可选项元素上添加class="tabable"此内容,以便我们稍后选择它们。(不要忘记下面的代码中的“。”类选择器前缀)

var lastTabIndex = 10;
function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFOcusIn
    var curIndex = currentElement.tabIndex; //get current elements tab index
    if(curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
        curIndex = 0;
    }
    var tabbables = document.querySelectorAll(".tabable"); //get all tabable elements
    for(var i=0; i<tabbables.length; i++) { //loop through each element
        if(tabbables[i].tabIndex == (curIndex+1)) { //check the tabindex to see if it's the element we want
            tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
            break;
        }
    }
}

16
无需在每个元素上都添加名称的解决方案(因为可行的话,有很多方法可以解决)将是理想的。
JadziaMD 2011年

3
好,这是表格吗?如果你想要的所有元素的输入元素,可以更换线var tabbables = document.getElementsByName("tabable");var tabbables = document.getElementsByTagName("input");替代
布莱恩Glaz

var tabbables = document.querySelectorAll("input, textarea, button")// IE8 +,无需修改HTML即可获取所有标签的引用。
格雷格

2
class =“ tabbable”而不是使用name属性
Chris F Carroll

4
请注意,使用flexbox时,DOM中元素的顺序不同于浏览器中视觉上的顺序。当您使用flexbox更改元素的顺序时,仅选择下一个tabbable元素不起作用。
哈涅夫

75

我从未实现过,但是我研究了类似的问题,这就是我会尝试的方法。

先尝试一下

首先,我将看看您是否可以简单地为当前具有焦点的元素上的Tab键触发一个keypress事件。对于不同的浏览器,可能会有不同的方法来执行此操作。

如果那不起作用,那么您将不得不更加努力地工作……

引用jQuery实现,您必须:

  1. 收听Tab和Shift + Tab
  2. 知道哪些元素是可制表的
  3. 了解制表符顺序的工作方式

1.收听Tab和Shift + Tab

收听Tab和Shift + Tab可能在网络上的其他地方很常见,所以我将跳过这一部分。

2.知道哪些元素是可制表的

知道哪些元素是可制表的比较棘手。基本上,如果元素是可聚焦的并且没有tabindex="-1"设置属性,则该元素是可制表的。因此,我们必须询问哪些元素是可聚焦的。以下元素是可聚焦的:

  • inputselecttextareabutton,和object元素没有被禁用。
  • a以及area具有href或具有要tabindex设置的数值的元素。
  • 具有要tabindex设置的数值的任何元素。

此外,仅在以下情况下元素才是可聚焦的:

  • 它的祖先都不是display: none
  • 的计算值visibilityvisible。这意味着要visibility设置的最近祖先的值必须为visible。如果没有祖先visibility设置,则计算值为visible

更多详细信息,请参见另一个堆栈溢出答案

3.了解选项卡顺序的工作方式

文档中元素的制表符顺序由tabindex属性控制。如果未设置任何值,tabindex则有效为0

tabindex文档的顺序为:1、2、3,…,0。

最初,当body元素(或没有元素)具有焦点时,制表顺序中的第一个元素是最低的非零值tabindex。如果多个元素相同tabindex,则按文档顺序进行操作,直到到达具有该元素的最后一个元素tabindex。然后,您移至下一个最低位置tabindex,该过程继续。最后,用零(或为空)结束那些元素tabindex


37

我为此目的构建了一些东西:

focusNextElement: function () {
    //add all elements we want to include in our selection
    var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
    if (document.activeElement && document.activeElement.form) {
        var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
        function (element) {
            //check for visibility while always include the current activeElement 
            return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
        });
        var index = focussable.indexOf(document.activeElement);
        if(index > -1) {
           var nextElement = focussable[index + 1] || focussable[0];
           nextElement.focus();
        }                    
    }
}

特征:

  • 可配置焦点元素集
  • 不需要jQuery
  • 适用于所有现代浏览器
  • 快速轻巧

2
这是最有效和资源友好的解决方案。谢谢!这是我完整的工作脚本:stackoverflow.com/a/40686327/1589669
eapo

我在下面添加了一个代码段,以包含通过显式TabIndex focussable.sort(sort_by_TabIndex)进行排序的功能
-DavB.cs,

1
最好的 !它必须是如此复杂:nextElementSibling可能无法集中,下一个可能不会是同级。
Tinmarino '19

好的方法,但是它应该允许任何非类型的输入hidden,也可以覆盖textareaselect
卢塞罗

23

我创建了一个简单的jQuery插件来执行此操作。它使用jQuery UI的':tabbable'选择器来查找下一个'tabbable'元素并选择它。

用法示例:

// Simulate tab key when element is clicked 
$('.myElement').bind('click', function(event){
    $.tabNext();
    return false;
});

8

答案的核心在于找到下一个元素:

  function findNextTabStop(el) {
    var universe = document.querySelectorAll('input, button, select, textarea, a[href]');
    var list = Array.prototype.filter.call(universe, function(item) {return item.tabIndex >= "0"});
    var index = list.indexOf(el);
    return list[index + 1] || list[0];
  }

用法:

var nextEl = findNextTabStop(element);
nextEl.focus();

注意,我不在乎优先级tabIndex


3
如果tabindex顺序与文档顺序相反怎么办?我认为该数组必须按tabindex编号然后按文档顺序排序
Chris F Carroll 2015年

是的,那将更加“符合规范”。我不知道边缘的情况下,关于父元素,等等
安德烈Werlang

如果不是这些标签之一的项目具有tabindex属性怎么办?
Matt Pennington

1
@MattPennington它将被忽略。过滤器是(尝试)加快搜索速度,随时可以调整。
安德烈Werlang

3

如以上评论中所述,我认为没有任何浏览器会公开制表符顺序信息。这里是浏览器如何以Tab键顺序获取下一个元素的简化示意图:

var allowedTags = {input: true, textarea: true, button: true};

var walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode: function(node)
    {
      if (node.localName in allowedTags)
        return NodeFilter.FILTER_ACCEPT;
      else
        NodeFilter.FILTER_SKIP;
    }
  },
  false
);
walker.currentNode = currentElement;
if (!walker.nextNode())
{
  // Restart search from the start of the document
  walker.currentNode = walker.root;
  walker.nextNode();
}
if (walker.currentNode && walker.currentNode != walker.root)
  walker.currentNode.focus();

这仅考虑一些标签,并忽略tabindex属性,但根据您要实现的目标可能就足够了。


3

似乎可以检查tabIndex元素的属性以确定它是否可聚焦。不可聚焦的元素具有tabindex“ -1”。

然后,您只需要知道制表位的规则:

  • tabIndex="1" 具有最高优先级。
  • tabIndex="2" 具有第二高的优先级。
  • tabIndex="3" 是下一个,依此类推。
  • tabIndex="0" (或默认情况下可选项)的优先级最低。
  • tabIndex="-1" (或默认情况下不可制表)不用作制表位。
  • 对于两个具有相同tabIndex的元素,在DOM中最先出现的元素具有更高的优先级。

这是一个如何使用纯Javascript依次构建制表位列表的示例:

function getTabStops(o, a, el) {
    // Check if this element is a tab stop
    if (el.tabIndex > 0) {
        if (o[el.tabIndex]) {
            o[el.tabIndex].push(el);
        } else {
            o[el.tabIndex] = [el];
        }
    } else if (el.tabIndex === 0) {
        // Tab index "0" comes last so we accumulate it seperately
        a.push(el);
    }
    // Check if children are tab stops
    for (var i = 0, l = el.children.length; i < l; i++) {
        getTabStops(o, a, el.children[i]);
    }
}

var o = [],
    a = [],
    stops = [],
    active = document.activeElement;

getTabStops(o, a, document.body);

// Use simple loops for maximum browser support
for (var i = 0, l = o.length; i < l; i++) {
    if (o[i]) {
        for (var j = 0, m = o[i].length; j < m; j++) {
            stops.push(o[i][j]);
        }
    }
}
for (var i = 0, l = a.length; i < l; i++) {
    stops.push(a[i]);
}

我们首先遍历DOM,依次收集所有制表位及其索引。然后,我们汇总最终列表。请注意,我们tabIndex="0"在列表的末尾添加了带有tabIndex1、2、3等的项目之后的。

对于完整的示例,您可以使用“ enter”键四处浏览,请查看此小提琴


2

Tabbable是一个小型JS程序包,它为您提供按Tab键顺序列出的所有Tabbable元素的列表。因此,您可以在该列表中找到您的元素,然后专注于下一个列表条目。

该程序包可以正确处理其他答案中提到的复杂边缘情况(例如,没有祖先可以display: none)。而且它不依赖jQuery!

在撰写本文时(版本1.1.1),它有一个警告,即它不支持IE8,并且浏览器的错误阻止了它的contenteditable正确处理。


2
function focusNextElement(){
  var focusable = [].slice.call(document.querySelectorAll("a, button, input, select, textarea, [tabindex], [contenteditable]")).filter(function($e){
    if($e.disabled || ($e.getAttribute("tabindex") && parseInt($e.getAttribute("tabindex"))<0)) return false;
    return true;
  }).sort(function($a, $b){
    return (parseFloat($a.getAttribute("tabindex") || 99999) || 99999) - (parseFloat($b.getAttribute("tabindex") || 99999) || 99999);
  });
  var focusIndex = focusable.indexOf(document.activeElement);
  if(focusable[focusIndex+1]) focusable[focusIndex+1].focus();
};

1

这是我关于SO的第一篇文章,因此我没有足够的声誉来评论已接受的答案,但是我不得不将代码修改为以下内容:

export function focusNextElement () {
  //add all elements we want to include in our selection
  const focussableElements = 
    'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled])'
  if (document.activeElement && document.activeElement.form) {
      var focussable = Array.prototype.filter.call(
        document.activeElement.form.querySelectorAll(focussableElements),
      function (element) {
          // if element has tabindex = -1, it is not focussable
          if ( element.hasAttribute('tabindex') && element.tabIndex === -1 ){
            return false
          }
          //check for visibility while always include the current activeElement 
          return (element.offsetWidth > 0 || element.offsetHeight > 0 || 
            element === document.activeElement)
      });
      console.log(focussable)
      var index = focussable.indexOf(document.activeElement);
      if(index > -1) {
         var nextElement = focussable[index + 1] || focussable[0];
         console.log(nextElement)
         nextElement.focus()
      }                    
  }
}

将var更改为常数并不重要。主要的变化是我们摆脱了检查tabindex!=“-1”的选择器。然后,如果该元素具有属性tabindex并将其设置为“ -1”,则我们认为它不是可聚焦的。

我需要更改它的原因是因为在向时添加tabindex =“-1”时<input>,该元素仍被认为是可聚焦的,因为它与“ input [type = text]:not([disabled])”选择器匹配。我的更改等效于“如果我们是非禁用文本输入,并且我们具有tabIndex属性,并且该属性的值为-1,那么我们不应被视为可聚焦。

我相信,当接受答案的作者编辑他们的答案以解释tabIndex属性时,他们做的并不正确。如果不是这种情况,请告诉我


1

还有就是tabindex属性可以在组件中设置属性。它指定选择一个并按Tab时应按哪些顺序迭代输入组件。大于0的值保留给自定义导航,0为“自然顺序”(因此,如果为第一个元素设置,其行为会有所不同),-1表示键盘无法聚焦:

<!-- navigate with tab key: -->
<input tabindex="1" type="text"/>
<input tabindex="2" type="text"/>

也可以将其设置为文本输入字段以外的其他内容,但是如果有的话,在此处执行的操作不是很明显。即使导航有效,将“自然顺序”用于其他任何事物也可能比非常明显的用户输入元素更好。

不,您完全不需要JQuery或任何脚本来支持此自定义导航路径。您可以在服务器端实现它,而无需任何JavaScript支持。另一方面,该属性在React框架中也可以正常工作,但不需要。


0

这是专注于下一个元素的更完整的版本。它遵循规范准则,并使用tabindex对元素列表进行正确排序。如果要获取上一个元素,还可以定义一个反向变量。

function focusNextElement( reverse, activeElem ) {
  /*check if an element is defined or use activeElement*/
  activeElem = activeElem instanceof HTMLElement ? activeElem : document.activeElement;

  let queryString = [
      'a:not([disabled]):not([tabindex="-1"])',
      'button:not([disabled]):not([tabindex="-1"])',
      'input:not([disabled]):not([tabindex="-1"])',
      'select:not([disabled]):not([tabindex="-1"])',
      '[tabindex]:not([disabled]):not([tabindex="-1"])'
      /* add custom queries here */
    ].join(','),
    queryResult = Array.prototype.filter.call(document.querySelectorAll(queryString), elem => {
      /*check for visibility while always include the current activeElement*/
      return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem === activeElem;
    }),
    indexedList = queryResult.slice().filter(elem => {
      /* filter out all indexes not greater than 0 */
      return elem.tabIndex == 0 || elem.tabIndex == -1 ? false : true;
    }).sort((a, b) => {
      /* sort the array by index from smallest to largest */
      return a.tabIndex != 0 && b.tabIndex != 0 
        ? (a.tabIndex < b.tabIndex ? -1 : b.tabIndex < a.tabIndex ? 1 : 0) 
        : a.tabIndex != 0 ? -1 : b.tabIndex != 0 ? 1 : 0;
    }),
    focusable = [].concat(indexedList, queryResult.filter(elem => {
      /* filter out all indexes above 0 */
      return elem.tabIndex == 0 || elem.tabIndex == -1 ? true : false;
    }));

  /* if reverse is true return the previous focusable element
     if reverse is false return the next focusable element */
  return reverse ? (focusable[focusable.indexOf(activeElem) - 1] || focusable[focusable.length - 1]) 
    : (focusable[focusable.indexOf(activeElem) + 1] || focusable[0]);
}

0

这是对@Kano@Mx提供的出色解决方案的潜在增强 。如果要保留TabIndex的顺序,请在中间添加以下排序:

// Sort by explicit Tab Index, if any
var sort_by_TabIndex = function (elementA, elementB) {
    let a = elementA.tabIndex || 1;
    let b = elementB.tabIndex || 1;
    if (a < b) { return -1; }
    if (a > b) { return 1; }
    return 0;
}
focussable.sort(sort_by_TabIndex);

0

您可以这样称呼:

标签:

$.tabNext();

Shift + Tab:

$.tabPrev();

<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
(function($){
	'use strict';

	/**
	 * Focusses the next :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
	 * Does not take into account that the taborder might be different as the :tabbable elements order
	 * (which happens when using tabindexes which are greater than 0).
	 */
	$.focusNext = function(){
		selectNextTabbableOrFocusable(':focusable');
	};

	/**
	 * Focusses the previous :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
	 * Does not take into account that the taborder might be different as the :tabbable elements order
	 * (which happens when using tabindexes which are greater than 0).
	 */
	$.focusPrev = function(){
		selectPrevTabbableOrFocusable(':focusable');
	};

	/**
	 * Focusses the next :tabable element.
	 * Does not take into account that the taborder might be different as the :tabbable elements order
	 * (which happens when using tabindexes which are greater than 0).
	 */
	$.tabNext = function(){
		selectNextTabbableOrFocusable(':tabbable');
	};

	/**
	 * Focusses the previous :tabbable element
	 * Does not take into account that the taborder might be different as the :tabbable elements order
	 * (which happens when using tabindexes which are greater than 0).
	 */
	$.tabPrev = function(){
		selectPrevTabbableOrFocusable(':tabbable');
	};

    function tabIndexToInt(tabIndex){
        var tabIndexInded = parseInt(tabIndex);
        if(isNaN(tabIndexInded)){
            return 0;
        }else{
            return tabIndexInded;
        }
    }

    function getTabIndexList(elements){
        var list = [];
        for(var i=0; i<elements.length; i++){
            list.push(tabIndexToInt(elements.eq(i).attr("tabIndex")));
        }
        return list;
    }

    function selectNextTabbableOrFocusable(selector){
        var selectables = $(selector);
        var current = $(':focus');

        // Find same TabIndex of remainder element
        var currentIndex = selectables.index(current);
        var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
        for(var i=currentIndex+1; i<selectables.length; i++){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }

        // Check is last TabIndex
        var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return a-b});
        if(currentTabIndex === tabIndexList[tabIndexList.length-1]){
            currentTabIndex = -1;// Starting from 0
        }

        // Find next TabIndex of all element
        var nextTabIndex = tabIndexList.find(function(element){return currentTabIndex<element;});
        for(var i=0; i<selectables.length; i++){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === nextTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }
    }

	function selectPrevTabbableOrFocusable(selector){
		var selectables = $(selector);
		var current = $(':focus');

		// Find same TabIndex of remainder element
        var currentIndex = selectables.index(current);
        var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
        for(var i=currentIndex-1; 0<=i; i--){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }

        // Check is last TabIndex
        var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return b-a});
        if(currentTabIndex <= tabIndexList[tabIndexList.length-1]){
            currentTabIndex = tabIndexList[0]+1;// Starting from max
        }

        // Find prev TabIndex of all element
        var prevTabIndex = tabIndexList.find(function(element){return element<currentTabIndex;});
        for(var i=selectables.length-1; 0<=i; i--){
            if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === prevTabIndex){
                selectables.eq(i).focus();
                return;
            }
        }
	}

	/**
	 * :focusable and :tabbable, both taken from jQuery UI Core
	 */
	$.extend($.expr[ ':' ], {
		data: $.expr.createPseudo ?
			$.expr.createPseudo(function(dataName){
				return function(elem){
					return !!$.data(elem, dataName);
				};
			}) :
			// support: jQuery <1.8
			function(elem, i, match){
				return !!$.data(elem, match[ 3 ]);
			},

		focusable: function(element){
			return focusable(element, !isNaN($.attr(element, 'tabindex')));
		},

		tabbable: function(element){
			var tabIndex = $.attr(element, 'tabindex'),
				isTabIndexNaN = isNaN(tabIndex);
			return ( isTabIndexNaN || tabIndex >= 0 ) && focusable(element, !isTabIndexNaN);
		}
	});

	/**
	 * focussable function, taken from jQuery UI Core
	 * @param element
	 * @returns {*}
	 */
	function focusable(element){
		var map, mapName, img,
			nodeName = element.nodeName.toLowerCase(),
			isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex'));
		if('area' === nodeName){
			map = element.parentNode;
			mapName = map.name;
			if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map'){
				return false;
			}
			img = $('img[usemap=#' + mapName + ']')[0];
			return !!img && visible(img);
		}
		return ( /^(input|select|textarea|button|object)$/.test(nodeName) ?
			!element.disabled :
			'a' === nodeName ?
				element.href || isTabIndexNotNaN :
				isTabIndexNotNaN) &&
			// the element and all of its ancestors must be visible
			visible(element);

		function visible(element){
			return $.expr.filters.visible(element) && !$(element).parents().addBack().filter(function(){
				return $.css(this, 'visibility') === 'hidden';
			}).length;
		}
	}
})(jQuery);
</script>

<a tabindex="5">5</a><br>
<a tabindex="20">20</a><br>
<a tabindex="3">3</a><br>
<a tabindex="7">7</a><br>
<a tabindex="20">20</a><br>
<a tabindex="0">0</a><br>

<script>
var timer;
function tab(){
    window.clearTimeout(timer)
    timer = window.setInterval(function(){$.tabNext();}, 1000);
}
function shiftTab(){
    window.clearTimeout(timer)
    timer = window.setInterval(function(){$.tabPrev();}, 1000);
}
</script>
<button tabindex="-1" onclick="tab()">Tab</button>
<button tabindex="-1" onclick="shiftTab()">Shift+Tab</button>

</body>
</html>

我修改了jquery.tabbable插件来完成。


该答案的重复项,由该jQuery插件的创建者发布。
mbomb007

0

死灵法师。
我有大量的0-tabIndexes,我想通过键盘进行导航。
因为在那种情况下,只有元素的ORDER才重要,所以我使用document.createTreeWalker

因此,首先创建过滤器(只需要[visible]元素,这些元素的属性“ tabIndex”具有NUMERICAL值)。

然后,设置根节点,您不想在该根节点上进行搜索。在我的情况下,this.m_tree是包含可切换树的ul元素。如果您想要整个文档,只需将替换this.m_treedocument.documentElement

然后,将当前节点设置为当前活动元素:

ni.currentNode = el; // el = document.activeElement

然后您返回ni.nextNode()ni.previousNode()

注意:
如果您具有tabIndices!= 0并且元素顺序不是tabIndex顺序,则这将不会以正确的顺序返回选项卡。如果tabIndex = 0,则tabOrder始终是元素顺序,因此(在这种情况下)它起作用的原因。

protected createFilter(fn?: (node: Node) => number): NodeFilter
{
    // Accept all currently filtered elements.
    function acceptNode(node: Node): number 
    {
        return NodeFilter.FILTER_ACCEPT;
    }

    if (fn == null)
        fn = acceptNode;


    // Work around Internet Explorer wanting a function instead of an object.
    // IE also *requires* this argument where other browsers don't.
    const safeFilter: NodeFilter = <NodeFilter><any>fn;
    (<any>safeFilter).acceptNode = fn;

    return safeFilter;
}



protected createTabbingFilter(): NodeFilter
{
    // Accept all currently filtered elements.
    function acceptNode(node: Node): number 
    {
        if (!node)
            return NodeFilter.FILTER_REJECT;

        if (node.nodeType !== Node.ELEMENT_NODE)
            return NodeFilter.FILTER_REJECT;

        if (window.getComputedStyle(<Element>node).display === "none")
            return NodeFilter.FILTER_REJECT;

        // "tabIndex": "0"
        if (!(<Element>node).hasAttribute("tabIndex"))
            return NodeFilter.FILTER_SKIP;

        let tabIndex = parseInt((<Element>node).getAttribute("tabIndex"), 10);
        if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
            return NodeFilter.FILTER_SKIP;

        // if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;

        return NodeFilter.FILTER_ACCEPT;
    }

    return this.createFilter(acceptNode);
}


protected getNextTab(el: HTMLElement): HTMLElement
{
    let currentNode: Node;
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker

    // let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
    // let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
    let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);

    ni.currentNode = el;

    while (currentNode = ni.nextNode())
    {
        return <HTMLElement>currentNode;
    }

    return el;
}


protected getPreviousTab(el: HTMLElement): HTMLElement
{
    let currentNode: Node;
    let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);
    ni.currentNode = el;

    while (currentNode = ni.previousNode())
    {
        return <HTMLElement>currentNode;
    }

    return el;
}

注意while循环

while (currentNode = ni.nextNode())
{
    // Additional checks here
    // if(condition) return currentNode;
    // else the loop continues;
    return <HTMLElement>currentNode; // everything is already filtered down to what we need here
}

仅在您有其他条件时才存在,您无法在传递给createTreeWalker的过滤器中进行过滤。

请注意,这是TypeScript,您需要删除冒号(:)后面和尖括号(<>)之间的所有标记,例如 <Element>或,:(node: Node) => number以获得有效的JavaScript。

作为服务,已转译的JS:

"use strict";
function createFilter(fn) {
    // Accept all currently filtered elements.
    function acceptNode(node) {
        return NodeFilter.FILTER_ACCEPT;
    }
    if (fn == null)
        fn = acceptNode;
    // Work around Internet Explorer wanting a function instead of an object.
    // IE also *requires* this argument where other browsers don't.
    const safeFilter = fn;
    safeFilter.acceptNode = fn;
    return safeFilter;
}
function createTabbingFilter() {
    // Accept all currently filtered elements.
    function acceptNode(node) {
        if (!node)
            return NodeFilter.FILTER_REJECT;
        if (node.nodeType !== Node.ELEMENT_NODE)
            return NodeFilter.FILTER_REJECT;
        if (window.getComputedStyle(node).display === "none")
            return NodeFilter.FILTER_REJECT;
        // "tabIndex": "0"
        if (!node.hasAttribute("tabIndex"))
            return NodeFilter.FILTER_SKIP;
        let tabIndex = parseInt(node.getAttribute("tabIndex"), 10);
        if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
            return NodeFilter.FILTER_SKIP;
        // if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;
        return NodeFilter.FILTER_ACCEPT;
    }
    return createFilter(acceptNode);
}
function getNextTab(el) {
    let currentNode;
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
    // let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
    // let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
    let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
    ni.currentNode = el;
    while (currentNode = ni.nextNode()) {
        return currentNode;
    }
    return el;
}
function getPreviousTab(el) {
    let currentNode;
    let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
    ni.currentNode = el;
    while (currentNode = ni.previousNode()) {
        return currentNode;
    }
    return el;
}

-1

您是否为要循环浏览的每个元素指定了自己的tabIndex值?如果是这样,您可以尝试以下操作:

var lasTabIndex = 10; //Set this to the highest tabIndex you have
function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn 

    var curIndex = $(currentElement).attr('tabindex'); //get the tab index of the current element
    if(curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
        curIndex = 0;
    }
    $('[tabindex=' + (curIndex + 1) + ']').focus(); //set focus on the element that has a tab index one greater than the current tab index
}

您正在使用jquery,对不对?


我们没有使用JQuery,因为它破坏了应用程序。:/
JadziaMD 2011年

好吧,我想我可以不用使用jquery进行重写,请
花点时间

我们感兴趣的每个元素都设置了标签索引值。
JadziaMD 2011年

-1

我检查了上述解决方案,发现它们很长。只需一行代码即可完成:

currentElement.nextElementSibling.focus();

要么

currentElement.previousElementSibling.focus();

这里currentElement可以是任何一个,即document.activeElement;如果当前元素在函数的上下文中,则可以为this。

我使用keydown事件跟踪了Tab和shift-tab事件

let cursorDirection = ''
$(document).keydown(function (e) {
    let key = e.which || e.keyCode;
    if (e.shiftKey) {
        //does not matter if user has pressed tab key or not.
        //If it matters for you then compare it with 9
        cursorDirection = 'prev';
    }
    else if (key == 9) {
        //if tab key is pressed then move next.
        cursorDirection = 'next';
    }
    else {
        cursorDirection == '';
    }
});

一旦有了光标方向,便可以使用nextElementSibling.focuspreviousElementSibling.focus方法


1
不幸的是,兄弟姐妹的顺序与制表符的顺序无关,除非碰巧是巧合,而且不能保证上一个/下一个兄弟姐妹甚至可以集中注意力。
劳伦斯·多尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.