
我有兩個完全重疊的divs;頂層有滾動行為,因為它有溢位的內容,我想保持滾動行為。
底層有不同的部分,有不同的點擊處理程式;圖片中的框(X,Y,Z)。
如何在保持頂層滾動的同時為底層提供點擊處理程式?
我已經嘗試過 CSS
pointer-events: none;,但它會轉發所有事件,這會導致頂層的滾動被禁用。我曾嘗試手動
dispatchEvent使用 javascript,但事件源無法正常作業。
這是DOM結構
<div>
<div
ref="layer2"
class="
layer2
h-96
cursor-pointer
text-2xl text-center
flex
space-x-4
items-center
justify-center
bg-green-400
"
style="width: 600px"
@click="handleLayer2"
>
<div
@click="handleSection('x')"
class="w-[200px] h-[8rem] bg-red-600 shadow-lg rounded h-24"
>
X
</div>
<div
@click="handleSection('y')"
class="w-[200px] h-[8rem] bg-red-600 shadow-lg rounded h-24"
>
Y
</div>
<div
@click="handleSection('z')"
class="w-[200px] h-[8rem] bg-red-600 shadow-lg rounded h-24"
>
Z
</div>
</div>
<div
class="
layer1
absolute
top-0
left-0
bg-pink-500
h-96
text-xl
whitespace-nowrap
text-center
opacity-70
overflow-scroll
pt-64
"
style="width: 600px"
@click="handleLayer1"
>
really long content ...
</div>
這是完整的復制品https://stackblitz.com/edit/vitejs-vite-dtxxqa?file=src/App.vue
uj5u.com熱心網友回復:
為了讓我的解釋更容易,我需要給每個 div 命名。我們稱絕對定位的 divtopDiv和下面的 div downDivs。
您還需要一個點擊處理程式topDiv本身。我們將使用該處理程式將事件“轉發”到downDivs.
在您的topDiv點擊處理程式中,您將執行以下操作:
// first hide the `topDiv`
event.target.hidden = true;
// Get the element underneath that also falls under the click location
let downDiv = document.elementFromPoint(event.clientX, event.clientY);
// Unhide the topDiv
event.target.hidden = false;
// We still need to confirm that the element gotten is actually a downDiv
if (!downDiv.classList.includes('down-div'))
return;
// Now we can dispatch a duplicate click event on the downDiv
downDiv.dispatchEvent(new MouseEvent('click', {
bubbles: true,
pageX: event.pageX,
pageY: event.pageY,
clientX: event.clientX,
clientY: event.clientY,
}));
// Now you can handle the clicks on the downDiv anyway you like :)
您可以閱讀本文以了解有關事件調度??的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477164.html
標籤:javascript html css dom
上一篇:如何檢查動態創建的按鈕被點擊的頻率,單獨的和總共的?
下一篇:更改Python字典中的鍵
