У меня есть следующая коробка:
<link rel = "preconnect" href = "https://fonts.googleapis.com">
<link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
<link href = "https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel = "stylesheet">
<div class = "tile-container">
<a class = "rectangle" href = " ">
<div class = "plus radius"></div>
<div class = "tile-label">
Sample <span class = "tile-accent">Text</span>
</div>
</a>
<style>
.tile-container {
display: flex;
}
.rectangle {
background-color:#0051a5;
margin: 5px;
display: block;
cursor: pointer;
height:200px;
flex: 1;
border-radius:23px;
position: relative; /*must be relative to act a tile-container for the tile-label class*/
}
.plus {
display:inline-block;
background:
linear-gradient(#73716d 0 0),
linear-gradient(#73716d 0 0),
#fff;
background-position:center;
background-size: 60% 2.5px,2.5px 60%;
background-repeat:no-repeat;
}
.radius {
border-radius:50%;
float: right;
width: 25px;
height: 25px;
position: absolute;
right: 25px;
top: 25px;
}
.tile-label {
font-family: 'PT Sans Narrow', sans-serif;
font-size: 25px;
text-transform: uppercase;
font-weight: 600;
color: white;
position: absolute;
bottom: 25px;
left: 25px;
}
.tile-accent {
color: white;
}
</style>
Итак, я пытался реализовать раскрывающуюся/складную функцию с помощью функции переключения javascript, но она не работала должным образом. По сути, всякий раз, когда пользователь нажимает на синее поле, оно должно раскрываться ниже, а под основным заголовком появляется скрытый текст, поэтому по сути это похоже на складную кнопку, где, если вы нажмете на нее, поле развернется ниже.
Я попытался использовать функцию переключения javascript и добавить класс CSS со скрытым списком и использовать его для переключения между каждым щелчком пользователя по полю, но он продолжал отображать текст над полем вместо расширения поля и текст, отображаемый под полем. основное название. Вместо этого текст отображался поверх поля или основного заголовка. Как я могу сделать так, чтобы всякий раз, когда пользователь нажимал на поле, оно плавно расширялось вниз, а под заголовком появлялся скрытый текст.
Это то, что я пробовал:
document.querySelector('.rectangle').addEventListener('click', function() {
this.classList.toggle('expanded');
const plus = this.querySelector('.plus');
plus.style.transform = this.classList.contains('expanded') ? 'rotate(45deg)' : 'rotate(0)';
});.tile-container {
display: flex;
}
.rectangle {
background-color: #0051a5;
margin: 5px;
display: block;
cursor: pointer;
height: 100px;
/* Reduced height for better visibility */
flex: 1;
border-radius: 23px;
position: relative;
transition: height 0.3s ease;
/* Add a transition for smooth animation */
}
.plus {
display: inline-block;
background: linear-gradient(#0051a5 0 0), linear-gradient(#0051a5 0 0), #fff;
background-position: center;
background-size: 60% 2.5px, 2.5px 60%;
background-repeat: no-repeat;
transition: transform 0.3s ease;
/* Add a transition for smooth animation */
}
.radius {
border-radius: 50%;
float: right;
width: 25px;
height: 25px;
position: absolute;
right: 25px;
top: 25px;
}
.tile-label {
font-family: 'PT Sans Narrow', sans-serif;
font-size: 25px;
text-transform: uppercase;
font-weight: 600;
color: #fff;
position: absolute;
bottom: 25px;
left: 25px;
}
.tile-accent {
color: #FFC72C;
}
.hidden-text {
display: none;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 18px;
color: #000;
/* Change text color as needed */
padding: 10px 25px;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
/* Background color for the hidden text area */
}
.expanded .rectangle {
height: 200px;
/* Adjust the expanded height as needed */
}
.expanded .hidden-text {
display: block;
}<head>
<link rel = "preconnect" href = "https://fonts.googleapis.com">
<link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
<link href = "https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel = "stylesheet">
</head>
<body>
<div class = "tile-container">
<a class = "rectangle" href = " ">
<div class = "plus radius"></div>
<div class = "tile-label">
Sample <span class = "tile-accent">Text</span>
</div>
</a>
<div class = "hidden-text">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</div>
</div>
</body>да, я включил в вопрос то, что пробовал



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Предлагаю поставить крестик (a) на div и убрать "блок"
.expanded.rectangle { убрать пробел.expanded+.hidden-text добавьте ссылку на одноуровневый комбинатор: https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinatordocument.querySelector('.rectangle')
.addEventListener('click', function() {
this.classList.toggle('expanded');
const plus = this.querySelector('.plus');
plus.style.transform = this.classList.contains('expanded') ? 'rotate(45deg)' : 'rotate(0)';
});.tile-container {
display: flex;
}
.rectangle {
background-color: #0051a5;
margin: 5px;
cursor: pointer;
height: 100px;
/* Reduced height for better visibility */
flex: 1;
border-radius: 23px;
position: relative;
transition: height 0.3s ease;
/* Add a transition for smooth animation */
}
.plus {
display: inline-block;
background: linear-gradient(#0051a5 0 0), linear-gradient(#0051a5 0 0), #fff;
background-position: center;
background-size: 60% 2.5px, 2.5px 60%;
background-repeat: no-repeat;
transition: transform 0.3s ease;
/* Add a transition for smooth animation */
}
.radius {
border-radius: 50%;
float: right;
width: 25px;
height: 25px;
position: absolute;
right: 25px;
top: 25px;
}
.tile-label {
font-family: 'PT Sans Narrow', sans-serif;
font-size: 25px;
text-transform: uppercase;
font-weight: 600;
color: #fff;
position: absolute;
bottom: 25px;
left: 25px;
}
.tile-accent {
color: #FFC72C;
}
.hidden-text {
display: none;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 18px;
color: #000;
/* Change text color as needed */
padding: 10px 25px;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
/* Background color for the hidden text area */
}
.expanded.rectangle {
height: 200px;
/* Adjust the expanded height as needed */
}
.expanded+.hidden-text {
display: block;
}<head>
<link rel = "preconnect" href = "https://fonts.googleapis.com">
<link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
<link href = "https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel = "stylesheet">
</head>
<body>
<div class = "tile-container">
<div class = "rectangle">
<div class = "plus radius"></div>
<div class = "tile-label">
Sample <span class = "tile-accent">Text</span>
</div>
</div>
<div class = "hidden-text">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</div>
</div>
</body>Возможно, то, что вам действительно нужно, это что-то вроде
1em; на основе контейнерного 25px шрифтаauto говорит: используйте размер содержимого.document.querySelector('.rectangle')
.addEventListener('click', function() {
this.classList.toggle('expanded');
const plus = this.querySelector('.plus');
plus.style.transform = this.classList.contains('expanded') ? 'rotate(45deg)' : 'rotate(0)';
});.tile-container {
padding: 5px;
font-size: 25px;
}
.rectangle {
background-color: #0051a5;
padding-right: 1em;
padding-top: 1em;
cursor: pointer;
border-radius: 1em;
display: grid;
grid-template-rows: 1fr auto;
grid-template-columns: auto 1em;
grid-template-areas: "sample plus" "extratext extratext";
}
.plus {
grid-area: plus;
background: linear-gradient(#0051a5 0 0), linear-gradient(#0051a5 0 0), #fff;
background-position: center;
background-size: 60% 2.5px, 2.5px 60%;
background-repeat: no-repeat;
transition: transform 0.3s ease;
}
.radius {
border-radius: 50%;
width: 1em;
height: 1em;
margin-right: 1em;
}
.tile-label {
grid-area: sample;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 1em;
text-transform: uppercase;
font-weight: 600;
color: #fff;
padding-left: 1em;
height: 2em;
}
.tile-accent {
color: #FFC72C;
}
.hidden-text {
grid-area: extratext;
display: none;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 0.75em;
background-color: #fff;
color: #000;
margin: 1em;
padding-top: 0.5em;
padding-left: 1em;
}
.expanded>.hidden-text {
display: block;
animation: fade-in 1s;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}<head>
<link rel = "preconnect" href = "https://fonts.googleapis.com">
<link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
<link href = "https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel = "stylesheet">
</head>
<body>
<div class = "tile-container">
<div class = "rectangle">
<div class = "plus radius"></div>
<div class = "tile-label">
Sample <span class = "tile-accent">Text</span>
</div>
<div class = "hidden-text">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</div>
</div>
</body>Когда я запустил фрагмент кода, текст в вашем коде отображается за пределами поля.
Итак, когда вы щелкаете по полю и когда оно расширяется вниз, видите ли вы пустое пространство, которое оно создает над заголовком? Я бы хотел, чтобы скрытый текст был там, если это возможно.
Шультезисс, это имеет смысл?
Я добавил пример «возможно, вы хотите», который на самом деле является лучшим способом сделать то, что, Я ДУМАЮ, вы хотите - просто измените CSS, связанный с визуальными эффектами, на «стилизацию» вещей по мере необходимости. Обратите внимание на небольшое изменение HTML, чтобы поместить материал в контейнер «прямоугольник».
Эй, да, однако, есть ли способ добавить плавный переход, который был раньше в вашем коде?
плавная анимация должна быть при нажатии на поле
Я добавил анимацию постепенного появления (также постепенного исчезновения, но на самом деле ее не использую), вы можете настроить ее по мере необходимости, возможно, некоторые комбинированные переходы и т. д., но, возможно, это не совсем часть вопроса.
не для внутреннего содержания.
В основном я искал плавную анимацию после нажатия на поле, например, когда оно расширяется.
Schuthesiss По сути, то же самое, что и в вашем старом коде, где после нажатия на флажок он плавно опускается вниз.
`transition: height 0,3s легкость;`, похоже, не работает в классе прямоугольника
Речь идет о display:none, возможно, нет необходимости вдаваться в подробности здесь, по моему мнению, ссылка: stackoverflow.com/q/3331353/125981
не могли бы вы вставить свой код JavaScript в свой вопрос?