2017-04-14 15 views
0

這真的很奇怪。 我在Vue組件中創建浮動側邊欄,因此需要更改固定和相對之間的css位置值。 所以我所做的是爲側邊欄元素提供ID,並在滾動事件中檢查頁面上的位置並更改了一些CSS值。工作在錯誤元素上的Vue.js風格

這是我的代碼。

created() { 
    document.addEventListener('scroll', this.handleScroll); 
}, 
destroyed() { 
    document.addEventListener('scroll', this.handleScroll); 
} 
/* ... */ 
handleScroll(e) { 
    var doc = document.documentElement; 
    var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); 
    var originWidth = $("#fields-to-move").width() + 2; 
    if(this.screen_no == 2){ 
    if (280 <= top) { 
     document.getElementById("fields-to-move").style.position = "fixed"; 
     document.getElementById("fields-to-move").style.top = 10 + 'px' ; 
     document.getElementById("fields-to-move").style.width = originWidth + 'px'; 
    } else { 
     document.getElementById("fields-to-move").style.position = "relative"; 
     document.getElementById("fields-to-move").style.top = 'auto' ; 
     document.getElementById("fields-to-move").style.width = originWidth + 'px'; 
    } 
} 
} 

「fields-to-move」是DOM元素的ID我要改變css。 它運作良好。

但問題是,上面的CSS(位置:固定,頂部:10px和寬度)也適用於其他元素沒有ID。

還有一件事情更需要提及。 帶有ID的元素是另一個用v-if條件裝入的子元素。 父元素被卸載後,css被應用到它後面的錯誤元素。

我不確定我的解釋是否足夠。如果您有任何問題超出我的問題,請讓我知道。

在此先感謝。

回答

0

如果你能提供的jsfiddle例如separeted會更容易幫助... 但我相信,這種行爲可以通過這裏介紹一些Vue的優化造成的:documentation

編輯: 嘗試執行整個邏輯nextScick中的「handleScroll」。