簡體   English   中英

禁止 click() 滾動頁面

[英]Disable click() from scrolling the page

我正在開發 Chrome 擴展程序,並嘗試使用 JavaScript 在滿足特定條件時單擊頁面上的元素,這很好用。

問題是,如果要單擊的元素不在屏幕上,瀏覽器將自動滾動,以便該元素在屏幕上。 我想讓我的代碼點擊元素而不自動滾動屏幕。

這是觸發點擊事件的代碼。

function isHidden(users, comment, sticky) {
    let userElement = comment.querySelector(`[data-testid="comment_author_link"]`);
    let currName = userElement.getAttribute("href");

    let shouldHide = users.includes(currName);

    let isStickied = comment.querySelector("._2wd-K5Djdc9TGPRGDgmkpX") !== null;

    if(shouldHide || (isStickied && sticky !== null)) {
        blockIndex = users.indexOf(currName);

        let level = comment.querySelector("._1RIl585IYPW6cmNXwgRz0J").innerHTML;
        level = parseInt(level.replace(/^\D+/g, ""), 10) - 1;

        let threadlines = comment.querySelectorAll(".threadline");
        threadlines[level]?.click();

        return true;
    }

    return false;
}

如果需要,我可以提供其他代碼片段,或者解釋更多關於我正在嘗試做的事情。

瀏覽器通常不會滾動到單擊的元素,除非鏈接具有像 '#myelement' 這樣的哈希並且元素 id 是id='myelement 如果是這種情況,您可能需要e.preventDefault()或在所有 js 事件上return false

 <button onclick="javascript: document.getElementById('myelement1').click()">Simulate el 1 click </button> <button onclick="javascript: document.getElementById('myelement6').click()">Simulate el 6 click - NO EFFECT </button> <a href='#myelement6' > <h1 id='myelement1'>1. Click me to sroll down - no js</h1> </a> <h1>2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1> <h1>3. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1> <h1>4. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1> <h1>5. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis, accusamus.</h1> <h1 id='myelement6'>6. Last element.</h1>

很難說沒有工作的例子。

編輯:

如果沒有任何效果,您可以在單擊之前存儲scrollTop值並將其設置回它之后的值(可能在滾動事件上或使用 setTimeout)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM