此功能将显示:empty
HTML元素的样式(设计为看起来像占位符),直到page load
,然后将一些内容注入这些元素,从而删除:empty
样式并显示内容。
如何在不使用:empty
并通过JS注入现有HTML内容的情况下简单地显示占位符?我希望已经有h1
,p
和img
的数据,并在page load
期间为这些元素放一个占位符。
var
image = document.querySelector('.sk-image'),
heading = document.querySelector('.sk-heading'),
paragraph = document.querySelector('.sk-paragraph');
var content = false;
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
if (content === false) {
content = true;
image.src = 'http://unsplash.it/400/400?image=564';
heading.innerHTML = 'Some heading';
paragraph.innerHTML = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa rerum porro aut laboriosam animi.';
} else {
content = false;
image.src = '';
heading.innerHTML = '';
paragraph.innerHTML = '';
}
}, 2000);
}, false);
body {
display: flex
}
.card {
width: 100%;
max-width: 300px;
min-height: 400px;
margin: 10px;
background: #fff;
border-bottom: 1px solid #d8d8d8;
box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
}
.card__image {
position: relative;
width: 100%;
height: 0;
padding-bottom: 60%;
background: #eee;
overflow: hidden;
}
.card__image:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(255, 255, 255, 0.65), rgba(0, 0, 0, 0));
transform: translateX(-100%);
animation: loading 1.5s infinite;
}
.card__image img {
position: relative;
max-width: 100%;
z-index: 1;
}
.card__content {
padding: 20px;
}
.card__heading {
margin-top: 0;
margin-bottom: 10px;
font-family: 'Alegreya Sans', sans-serif;
font-weight: 400;
}
.card__heading:empty {
width: 100%;
height: 35px;
background: #d8d8d8;
margin-bottom: 20px;
}
.card__paragraph {
margin: 0;
font-size: 20px;
line-height: 1.35;
}
.card__paragraph:empty {
width: 90%;
height: 20px;
background: #d8d8d8;
}
.button {
margin: 10px;
padding: 15px 20px;
background: #2aa1c0;
border: 0;
color: #fff;
}
.button:hover {
background: #0e647d;
}
@-moz-keyframes loading {
100% {
transform: translateX(100%);
}
}
@-webkit-keyframes loading {
100% {
transform: translateX(100%);
}
}
@-o-keyframes loading {
100% {
transform: translateX(100%);
}
}
@keyframes loading {
100% {
transform: translateX(100%);
}
}
<div class="card">
<div class="card__image">
<img class="sk-image" alt="" />
</div>
<div class="card__content">
<h1 class="card__heading sk-heading"></h1>
<p class="card__paragraph sk-paragraph"></p>
</div>
</div>
<div class="card">
<div class="card__image">
<img class="sk-image" alt="" />
</div>
<div class="card__content">
<h1 class="card__heading sk-heading"></h1>
<p class="card__paragraph sk-paragraph"></p>
</div>
</div>