簡體   English   中英

Javascript - 點擊功能產生意外結果

[英]Javascript - on-click function giving unexpected result

在我的項目中,我有一個 div,它設置為display: none; 默認情況下。 當用戶單擊圖像時,我使用 onclick 函數嘗試顯示圖像。 然而,這種方法由於某種原因不起作用。

這是我的 HTML:

<img onclick="hamburgerFunc()" class="hamburger-btn" width="38px" src="{% static 'hamburgericon.png' %}" alt="Image of hamburger icon"> 

<div class="box arrow-top"></div>
<script src="{% static 'home.js' %}"></script>

JS:

function hamburgerFunc(objs) {
    objs = document.getElementsByClassName("box arrow-top")
    objs.style.display = 'inline-block';
}

更新代碼:

.box.arrow-top:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: -15px;
    border-top: none;
    display: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid white;
  }

框箭頭頂部是我想在按下圖像后顯示的 div。 有人知道為什么這段代碼不起作用嗎? 謝謝你。

getElementsByClassName返回的不是單個元素,而是一個實時的 HTMLCollection。 您要么需要遍歷所有這些並分別為每個設置style 或者,如果您只希望在元素上直接訪問它objs[0].style.display = …

const objs = document.getElementsByClassName("box arrow-top")
objs[0].style.display = 'inline-block';

或者

const objs = document.getElementsByClassName("box arrow-top")
for (const obj of objs) {
  obj.style.display = 'inline-block';
}

或者,您可以使用querySelectorquerySelectorAll

const obj = document.querySelector(".box.arrow-top")
obj.style.display = 'inline-block';

或者如果你真的有多個元素:

const objs = document.querySelectorAll(".box.arrow-top")
for (const obj of objs) {
  obj.style.display = 'inline-block';
}

更新

:after創建偽元素后,這些元素不是 DOM 的一部分,無法選擇。

你要做的是去掉display: none; 從你的 css 規則。 例如將規則更改為.box.arrow-top.visible:after

.box.arrow-top.visible:after {
    content: " ";
    position: absolute;
    right: 30px;
    top: -15px;
    border-top: none;
    border-right: 15px solid transparent;
    border-left: 15px solid transparent;
    border-bottom: 15px solid white;
  }

然后做:

obj.style.classList.add("visible");

 function hamburgerFunc() { document.querySelector(".box.arrow-top").style.display = 'inline-block' }
 .box.arrow-top{ display:none; background:orange; padding:1em; position:relative; width: 38px; } .box.arrow-top:after { content: " "; position: absolute; border-top: none; border-right: 15px solid transparent; border-left: 15px solid transparent; border-bottom: 15px solid white; }
 <img onclick="hamburgerFunc()" class="hamburger-btn" width="38px" src="https://placekitten.com/200/200" alt="Image of hamburger icon"> <div class="box arrow-top"></div>

暫無
暫無

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

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