javascript
  • html
  • web-component
  • custom-element
  • 2016-07-12 30 views 1 likes 
    1

    我使用的是原生DOM編寫定製<select>元素(無聚合物)點擊標籤不注重定製元素(WebComponent的)

    我試圖用我的元素與<label>元素,並正確點擊觸發事件,我元素被點擊的標籤時,即:

    <label> 
        My Select: 
        <my-select placeholder="Please select one">...</my-select> 
    </label> 
    
    // or 
    
    <label for='mySelect1'>My Select:</label> 
    <my-select id='mySelect1' placeholder="Please select one">...</my-select> 
    

    但是這種行爲並沒有開箱的,即使我添加的tabindex,使其可成爲焦點

    這裏有一個精簡版的代碼和jsfiddle與s青梅基本的調試:只有https://jsfiddle.net/h56692ee/2/

    var MySelectOptionProto = Object.create(HTMLElement.prototype); 
    document.registerElement('my-select-option', { prototype: MySelectOptionProto}); 
    
    var MySelectProto = Object.create(HTMLElement.prototype); 
    MySelectProto.createdCallback = function() { 
        if (!this.getAttribute('tabindex')) { 
         this.setAttribute('tabindex', 0); 
        } 
        this.placeholder = document.createElement('span'); 
        this.placeholder.className = 'my-select-placeholder'; 
        this.appendChild(this.placeholder); 
    
        var selected = this.querySelector('my-select-option[selected]'); 
        this.placeholder.textContent = selected ? 
         selected.textContent : (this.getAttribute('placeholder') || ''); 
    }; 
    document.registerElement('my-select', { prototype: MySelectProto}); 
    

    回答

    1

    phrasing content元素可以通過<label>有針對性。

    因此,如果您要使用非標準(自主定製)元素,您必須自己管理焦點操作。

    相反,你可以選擇定義定製的內置元素將延長<select>元素,如下面的例子: https://jsfiddle.net/h56692ee/4/

    var MySelectProto = Object.create(HTMLSelectElement.prototype) 
    //... 
    document.registerElement('my-select', { prototype: MySelectProto, extends: "select" }) 
    

    你需要使用is屬性符號對於HTML:

    <label> 
        My Select: 
        <select is="my-select" placeholder="Please select one"> 
         <option>...</option> 
        </select> 
    </label> 
    

    更新在這2個職位的更多解釋:herethere

    +0

    我發現不得不使用'is'關鍵字進行擴展,因爲這意味着我的一些元素需要使用不同的html結構寫入其他元素。我選擇了包裝一個select元素並使用它來處理焦點。這將是很好,但能夠直接實現**措辭內容**界面 – Dogoku

    +0

    謝謝你的觀點。我和你一樣,然後我意識到,兩個自定義元素(有和沒有'是')都是出於不同的目的,所以現在我根據自己的需要使用兩者。但是標準還沒有完成,也許將來您也可以使用自主定製元素的內置語義。我已經更新了可能的解答鏈接,以解釋兩種語法之間的區別。 – Supersharp

    相關問題