2017-04-19 76 views
-3

我想讓用戶檢查/取消選中空格鍵或輸入鍵盤的複選框,我想使用JavaScript函數實現此功能。要檢查/取消選中使用JavaScript中的鍵盤複選框?

這是我的代碼的外觀部分:

<span class="sample" onClick="UdateComponent" tabindex="0" role="checkbox" aria-checked="" aria-decribedby=""> 

這個範圍我想包括onkeypress事件或者onkeydown事件實現是上面提到的功能,內部和約束我只需要使用Javascript這一點。

+7

爲什麼不使用複選框,它具有內置的此功能,並且可以以任何您想要的方式進行樣式設置? –

+0

我已經使用複選框,但我無法檢查/取消選中? –

+2

上面的標記中沒有複選框。 –

回答

0

我會強烈建議不要這樣做。使用input type="checkbox",結合label。這是他們的目的。你可以非常徹底地設計它們你甚至可以隱藏input type="checkbox"如果你想,只顯示label


但是你說過你不能使用input。所以是的,你可以用keypress處理程序來做到這一點。你大概也想要處理點擊。看評論:

// Handle toggline the "checkbox" 
 
// Expects the element as `this` and the event as `e` 
 
function toggleFakeCheckbox(e) { 
 
    // States as far as I can tell from 
 
    // https://www.w3.org/TR/wai-aria/states_and_properties#aria-checked 
 
    // and 
 
    // https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_checkbox_role 
 
    this.setAttribute(
 
    "aria-checked", 
 
    this.getAttribute("aria-checked") === "true" ? "false" : "true" 
 
); 
 
    // Avoid the default (spacebar in particular is problematic) 
 
    e.preventDefault(); 
 
    e.stopPropagation(); 
 
} 
 

 
// Get the element 
 
var sample = document.querySelector(".sample"); 
 

 
// Set up its handlers for click and keypress 
 
sample.addEventListener("click", toggleFakeCheckbox); 
 
sample.addEventListener("keypress", function(e) { 
 
    // Flag for whether to toggle 
 
    var toggle = false; 
 
    var keyCode; 
 
    if ("key" in e) { 
 
    // Modern user agent 
 
    toggle = e.key === " " || e.key === "Enter"; 
 
    } else { 
 
    // Fallback for older user agents 
 
    keyCode = e.which || e.keyCode; 
 
    toggle = keyCode === 32 || keyCode === 13; 
 
    } 
 
    if (toggle) { 
 
    toggleFakeCheckbox.call(this, e); 
 
    } 
 
}); 
 
// Give it focus for easy testing 
 
sample.focus();
/* Let's show the state of the checkbox */ 
 
[role=checkbox][aria-checked=true]:before { 
 
    content: '[x] ' 
 
} 
 
[role=checkbox][aria-checked=false]:before { 
 
    content: '[ ] ' 
 
}
<span class="sample" tabindex="0" role="checkbox" aria-checked="true" aria-decribedby="">Checkbox</span>

但再次:重新發明輪子是不是一件好事,即使您嘗試這樣做時,尊重所有的ARIA規則...

更新:確實,在IE瀏覽器中關注跨度並點擊空格鍵將我們移動到頁面的不同部分,儘管我們都阻止了默認操作(這足以阻止Firefox的操作)並停止了傳播。它爲什麼這樣做?因爲我們試圖重新發明輪子。這是一件壞事™。

相關問題