默认活动按钮处为橙色



我有 3 个按钮,当我单击每个按钮时,活动按钮具有橙色的 collor(:专注于 css,它的工作(,但是当我加载页面时,我想将第一个按钮设置为默认的活动按钮(所以它的颜色是橙色(。怎么做?我的代码是:

.HTML:

<div class="tabs">
<a class="btn black" rel="0" tabindex="1">1 button</a>
<a class="btn black" rel="1" tabindex="1">2 button</a>
<a class="btn black" rel="2" tabindex="1">3 button</a>
</div>

.CSS:

.btn {height:42px;}
.btn.black:focus {background:#ff6600;}
.btn.black:active {background:#ff6600;}

您可以使用focus()方法将焦点设置在该元素上

.btn {
height: 42px;
}
.btn.black:focus {
background: #ff6600;
}
.btn.black:active {
background: #ff6600;
}
<div class="tabs">
<a id="abc" class="btn black" rel="0" tabindex="1">1 button</a>
<a class="btn black" rel="1" tabindex="1">2 button</a>
<a class="btn black" rel="2" tabindex="1">3 button</a>
</div>
<script>
document.getElementById("abc").focus()
</script>

.btn {
height: 42px;
}
.btn.black:focus {
background: #ff6600;
}
.btn.black:active {
background: #ff6600;
}
<div>
Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some
content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content
Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some
content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content Some content
Some content
</div>
<div class="tabs">
<a id="abc" class="btn black" rel="0" tabindex="1">1 button</a>
<a class="btn black" rel="1" tabindex="1">2 button</a>
<a class="btn black" rel="2" tabindex="1">3 button</a>
</div>
<script>
var cursorFocus = function(elem) {
var x = window.scrollX,
y = window.scrollY;
elem.focus();
window.scrollTo(x, y);
}
cursorFocus(document.getElementById('abc'));
</script>

如果您使用按钮而不是锚点,则可以使用自动对焦,如下所示

<div class="tabs">
<button type="button" class="btn black" rel="0" autofocus>1 button</button>
<button type="button" class="btn black" rel="1" tabindex="1">2 button</button>
<button type="button" class="btn black" rel="2" tabindex="1">3 button</button>
</div>

在HTML5中,您可以使用autofocus,但您需要从<a>元素切换到<button>元素:

<div class="tabs">
<button class="btn black" rel="0" tabindex="1" autofocus>1 button</button>
<button class="btn black" rel="1" tabindex="1">2 button</button>
<button class="btn black" rel="2" tabindex="1">3 button</button>
</div>

不需要 JavaScript :)

编辑: 链接到自动对焦文档

最新更新