因此,本質上我想要一個元素,當點擊時,觸發一個jQuery腳本,添加或刪除類(在這種情況下,我添加一個將background-image css屬性更改爲只有該特定元素的類)。jQuery腳本添加/刪除類成功添加類,但不能刪除相同的類
function readMore() {
var subID = event.target.id;
var footerTarget = $('[id='+subID+'][class="articleFooter"]');
var newTarget = $('[id='+subID+'][class="showArticlePara"]');
newTarget.toggle();
var footerTarget = $('[id='+subID+'][class="articleFooter"]');
if (newTarget.css("display") == "block") {
footerTarget.addClass("changeBackgroundImage");
}
else {
footerTarget.removeClass("changeBackgroundImage");
}
alert(footerTarget.class());
}
$(document).ready(function() {
});
.articleSection {
\t width: 100%;
\t display: block;
\t font-family: Trebuchet MS;
\t font-size: 1.1em;
\t color: white;
\t margin-bottom: 25px;
\t padding-bottom: 3px;
\t background-color: RGBA(255, 255, 255, 0.1);
\t box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
\t border-radius: 2px;
\t box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
-ms-box-sizing:border-box;
}
.articleContent {
\t /*height: 70px;*/
\t padding: 10px 15px 5px 15px;
\t box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
-ms-box-sizing:border-box;
}
.articleVotes {
}
.voteBox {
}
.articleFooter {
\t width: 100%;
\t height: 10px;
\t content: 'more';
\t background-image:url('../Images/Icons/showMoreBlack13030.png');
\t background-size: contain;
\t background-repeat: no-repeat;
\t background-position: center center;
\t transition: 0.2s ease-in-out;
}
.articleFooter:hover {
\t background-image: url('../Images/Icons/chevron13040Blue.png');
}
.changeBackgroundImage {
\t width: 100%;
\t height: 10px;
\t content: 'less';
\t background-image:url('../Images/Icons/showLessBlack13030.png');
\t background-size: contain;
\t background-repeat: no-repeat;
\t background-position: 15px center;
\t transition: 0.2s ease-in-out;
}
.changeBackgroundImage:hover {
\t background-image: url('../Images/Icons/chevron13040BlueRotated.png');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="articleSection">
<div class="articleContent">
<h2>Exciting new study shows that in any male group, at least one is gay</h2>
<div class="showArticlePara" id="one">
<p>
I really hope it's Luke, he's cute af.
</p>
</div>
</div>
<div class="articleVotes">
<div class="voteBox"></div>
</div>
<div class="articleFooter" id="one" onclick="readMore()"></div>
</div>
所以當我點擊.articleFooter
與id=subID
我已經與它改變使用簡單的jQuery toggle()
顯示屬性相關聯的段落的顯示。我嘗試過使用toggleClass()
,但這隻會添加該類,並不會在第二次點擊時將其刪除。
我終於嘗試的if/else
聲明,檢查如果先前影響款display: none
和添加或刪除基於結果的類,但再次這只是成功添加類,但未能在除去同一類第二次點擊。
感謝您的任何建議和/或幫助。
的jsfiddle:https://jsfiddle.net/hm3y3848/
對多個元素使用相同的id'one'。 ID意味着獨特。 – Titus
@Titus我知道,我知道,糟糕的禮儀和所有這些,但當時似乎是一個好主意,我希望它不會影響我目前的問題,因此本質上;一步一步來。 –
@PaulMcGlinchey - 這不僅僅是壞禮節,它實際上影響了JS和jQuery的功能。 。 。例如,選擇(在JS和jQuery中)多次在DOM中的id,將只返回具有該id的第一個元素。 – talemyn