У меня есть фоновое изображение внутри кнопки, которую я хотел бы вращать/переворачивать при нажатии кнопки. Фоновое изображение представляет собой стрелку вниз, и я хотел бы, чтобы оно перевернулось на стрелку вверх. Кнопка предназначена для складного ящика, поэтому я хотел бы, чтобы стрелка возвращалась назад, когда ящик закрывается. Кнопка открывает и закрывает ящик, а фоновое изображение применяется через CSS.
document.querySelectorAll(".collapsible").forEach((coll) => {
coll.addEventListener("click", () => {
coll.classList.toggle("active");
const content = coll.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
// Add this:
content.style.borderWidth = 0;
} else {
content.style.maxHeight = content.scrollHeight + "px";
// And this:
content.style.borderWidth = "1px";
}
});
});
function myFunction() {
var element = document.getElementById("toggling");
element.classList.toggle("toggled");
};
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition:
border 0.2s ease-out,
max-height 0.2s ease-out;
background-color: white;
border: 0px solid #D1D3D4;
border-radius: 3px;
}
.collapsible {
background-color: white;
color: #021032;
cursor: pointer;
padding: 14px;
width: 100%;
border: solid 1px #D1D3D4;
border-radius: 6px;
text-align: left;
outline: none;
font-size: 15px;
margin: 5px 0px;
}
button {
background-image: url("../images/upArrow.svg");
background-repeat: no-repeat;
background-position: right;
background-size: 25px;
font-weight: 900;
}
.toggled {
background-image: url("../images/downArrow.svg");
background-repeat: no-repeat;
background-position: right;
background-size: 25px;
font-weight: 900;
}
<button type = "button" class = "collapsible" onclick = "myFunction()" id = "toggling"> Consult Logs </button>
<div class = "content">
<div class = "column">
<p>Ensure the disc strength is not at “0”.</p>
</div>
<div class = "column">
<img src = "../images/discStrength.png" alt = "Picture of Logs">
</div>
</div>
<button type = "button" class = "collapsible" disabled> Ensure All Connectors to Nebuliser Boards are Fully Connected </button>
<button type = "button" class = "collapsible" onclick = "myFunction()" id = "toggling"> Loose Crimp Issue </button>
<div class = "content">
<div class = "column">
<p>Check that the wires and crimps are fully inserted into J1, J4, and trandsducer connectors.</p>
</div>
<div class = "column">
<img src = "../images/looseCrimp.png" alt = "Picture of Connectors">
</div>
</div>
Нет, к сожалению, нет.
вам нужно будет переключить класс, который применяет преобразование поворота с помощью css. или вы можете вращать прямо из JS. не стесняйтесь публиковать то, что вы пробовали ;)
переключить класс на .collapsible.open{}
, который содержит изображение diff или преобразование
Не могли бы вы показать мне, как это будет выглядеть? Я все еще учусь, и я не уверен, как это реализовать.
поиск в google "как переключить класс с помощью javascript" и "как повернуть и элемент с помощью css"
Боже мой! Я сделал это, большое спасибо, это был отличный опыт обучения. Я обновлю вопрос с моей успешной попыткой. Вы, друзья, легенды.
Хм, возможно, я слишком взволнован, он применяется к идентификатору, но я бы хотел, чтобы он применялся к классу, потому что вы не можете кратно одному и тому же идентификатору, верно?
покажите нам ваш обновленный код. может быть, мы можем помочь больше :)
Я не хочу отвлекаться от вашего обучения, но я подумал, что хотел бы указать, что вы уже установили активный класс на своей кнопке. Это означает, что вы можете просто нажать на этот активный класс, чтобы повернуть значок.
Ниже я создал отдельный div, чтобы можно было просто поворачивать этот div, когда активный класс применяется к кнопке. Вы также можете сделать это с помощью псевдоэлемента ::after
и сохранить свою разметку чистой. Если бы у вас было два отдельных изображения, вы могли бы просто поменять местами фоновое изображение. Надеюсь, это вдохновит вас попробовать все эти варианты, чтобы продолжать изучать новые методы.
document.querySelectorAll(".collapsible").forEach((coll) => {
coll.addEventListener("click", () => {
coll.classList.toggle("active"); //<-- you're already toggling this class
const content = coll.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
// Add this:
content.style.borderWidth = 0;
} else {
content.style.maxHeight = content.scrollHeight + "px";
// And this:
content.style.borderWidth = "1px";
}
});
});
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition:
border 0.2s ease-out,
max-height 0.2s ease-out;
background-color: white;
border: 0px solid #D1D3D4;
border-radius: 3px;
}
.collapsible {
background-color: white;
color: #021032;
cursor: pointer;
padding: 14px;
width: 100%;
border: solid 1px #D1D3D4;
border-radius: 6px;
text-align: left;
outline: none;
font-size: 15px;
margin: 5px 0px;
}
button {
font-weight: 900;
/*
I put your background image in
its own div so I removed it from
the button styles.
I added flex to make it easier to
align the image and push it to the
right inside the button.
*/
display: flex;
justify-content: space-between;
align-items: center;
}
.icon {
/*
I just added an inline SVG so you
see it working in the snippet, but you
can use your existing local image.
*/
background-image: url("data:image/svg+xml,%3Csvg stroke='currentColor' fill='currentColor' stroke-width='0' viewBox='0 0 16 16' height='1em' width='1em' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M16 8A8 8 0 1 0 0 8a8 8 0 0 0 16 0zm-7.5 3.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11.5z'%3E%3C/path%3E%3C/svg%3E");
background-repeat: no-repeat;
background-size: 25px;
/*
Added height and width to the div
the same size as your background-size
since it doesn't have an content
*/
height: 25px;
width: 25px;
/*
Added a transition so it rotates smoothly
between the two states
*/
transition: rotate .25s ease-in-out;
}
button.active > .icon {
/*
When the button has the active class
apply the rotate to any direct child
with the clas of icon.
*/
rotate: 180deg;
}
<button type = "button" class = "collapsible"> Consult Logs <div class = "icon"><div></button>
<div class = "content">
<div class = "column">
<p>Ensure the disc strength is not at “0”.</p>
</div>
<div class = "column">
<img src = "../images/discStrength.png" alt = "Picture of Logs">
</div>
</div>
Спасибо, я все еще учусь, и я очень ценю это!
Отвечает ли это на ваш вопрос? Как повернуть фоновое изображение в контейнере?