簡體   English   中英

Javascript:使用原版 javascript 隱藏和顯示文本

[英]Javascript: hide and show text using vanilla javascript

我是 javascript 的新手。 我想要做的是使用 vanilla javascript 在點擊時隱藏和顯示一些文本。 我不知道我在做什么錯這里是代碼:

這是 HTML 代碼:

<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle- 
content" aria-hidden="true">some other text</span></p>
<a class="text-danger toggle-button" aria-controls="toggle-content">show more</a>

這是 javascript 代碼:

const a = document.querySelector('.toggle-button');

if(a){
a.addEventListener('click', () => {
const content = document.querySelector('.toggle-content');
const ariaHidden = content.getAttribute('aria-hidden');

content.setAttribute('aria-hidden', ariaHidden === 'true' ? 'false' : 'true');

const atext = content.getAttribute('aria-hidden') === 'true' ? 'Show' : 'Hide';

a.innerHTML = `${atext} more`;
});
}

這是 css 代碼:

.toggle-content {
display: none;
}

.toggle-content[aria-hidden="false"] {
display: block;
}

您在<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle- <!-- here you have added a line break which should not be inside an attribute --> content" aria-hidden="true">some other text</span></p>

 const a = document.querySelector('.toggle-button'); if(a){ a.addEventListener('click', () => { const content = document.querySelector('.toggle-content'); const ariaHidden = content.getAttribute('aria-hidden'); content.setAttribute('aria-hidden', ariaHidden === 'true'? 'false': 'true'); const atext = content.getAttribute('aria-hidden') === 'true'? 'Show': 'Hide'; a.innerHTML = `${atext} more`; }); }
 .toggle-content { display: none; }.toggle-content[aria-hidden="false"] { display: block; }
 <p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle-content" aria-hidden="true">some other text</span></p> <a class="text-danger toggle-button" aria-controls="toggle-content">show more</a>

您的第一個 p 標簽有問題,請正確寫入此標簽。 我嘗試簡化您的方法,嘗試為您的元素添加/刪除活動的 class,例如:

const a = document.querySelector('.toggle-button');
const content = document.querySelector('.toggle-content');

a.addEventListener('click', () => {
content.classList.includes('active') ? content.classList.remove('active') : content.classList.add('active');
});

.toggle-content {
display: none
}

.active {
display: block
}

為什么你使用 if(a),可能是因為你的元素還沒有出現,為了避免這樣的情況,嘗試將你的代碼包裝在document.onload中,它會在文檔准備好時被調用。

我猜你弄錯了。 改變這個:

const content = document.querySelector('.toggle-content');

至:

const content = document.querySelector('#toggle-content');

甚至更好

const content = document.getElementById('toggle-content');

暫無
暫無

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

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