javascript - Các kiểu CSS không áp dụng trên innerHTML
Tôi đang hiển thị một thẻ bootstrap với innerHTML trong file TS của mình nhưng các kiểu không áp dụng cho nội dung này, tôi nghĩ có thể là vì các kiểu được tải trước khi component hiển thị thẻ nên các kiểu không hoạt động, có lời khuyên nào về vấn đề này không? Tôi đang sử dụng Angular 12
mã TS của tôi:
constructor(private _route: ActivatedRoute, private router: Router) {
this.noticias = [
{
id: '1',
vTitulo: 'Convención anual de la Asociación Mexicana de Semilleros (AMSAC)',
dFecha: 'DIC 2021'
},
{
id: '2',
vTitulo: 'El “Arroz Auténtico Americano”',
dFecha: 'DIC 2021'
},
{
id: '3',
vTitulo: 'Se incrementa balanza comercial agroalimentaria',
dFecha: 'DIC 2021'
},
{
id: '4',
vTitulo: 'Ciencia e innovación en el campo, clave para evitar escasez de alimentos en 2050: Bayer',
dFecha: 'DIC 2021'
},
{
id: '5',
vTitulo: 'Corteva es reconocido por “Mejor programa de voluntariado”',
dFecha: 'DIC 2021'
}
]
$.when( $.ready ).then(() => {
const noticiasList = document.getElementById('noticiasList');
let displayNoticias = (noticias: any[]) => {
const htmlString = noticias
.map((noticia) => {
return `
<div class="card cardNoticias">
<div class="d-flex position-absolute top-0 end-0">
<h5 class="mb-0 fecha text-uppercase">${noticia.dFecha}</h5>
</div>
<div class="card-body card-body-noticiasList text-center d-flex align-items-center justify-content-center">
<h4 class="card-text fw-bold mt-3">${noticia.vTitulo}</h4>
<a href="" class="stretched-link"></a><!--Dentro del href se pondria el link hacia el articulo-->
</div>
</div>
`
})
.join('');
if(noticiasList) noticiasList.innerHTML = htmlString;
}
let filtradoNoticias = this.noticias.filter((noticia) => {
return (
noticia.vTitulo.toLowerCase().includes(this.busqueda.toLowerCase())
);
})
displayNoticias(filtradoNoticias);
})
}
Đây là nơi tôi đang hiển thị innerHTML
<div class="col-lg-12 ms-2 ps-lg-3 pe-lg-2 mt-2 mt-xl-2 mb-5">
<h1>NOTICIAS ENCONTRADAS</h1>
<div id="noticiasList">
</div>
</div>
Và các kiểu mà tôi muốn áp dụng cho thẻ
.noticiasList .cardNoticias{
background-color: gray;
}
.noticiasList .cardNoticias .card-body-noticiasList {
width: 100%;
padding-right: 30px;
}
.fecha {
background-color: lightgray;
margin-right: 1px;
text-align: center;
width: 30px;
}
Về cơ bản, ts nhận một chuỗi mà người dùng muốn tìm và lọc tiêu đề của tin tức, sau đó hiển thị những tin có chuỗi đó trong tiêu đề
Câu trả lời #1
noticiasList là id của phần tử, không phải là lớp được gán cho phần tử.
Vì vậy, để tham chiếu đến div đó trong CSS, bạn có thể muốn sử dụng bộ chọn # (dùng cho ID).
Vì vậy, đoạn CSS của bạn sẽ kết thúc như sau:
#noticiasList .cardNoticias{
background-color: gray;
}
#noticiasList .cardNoticias .card-body-noticiasList {
width: 100%;
padding-right: 30px;
}
.fecha {
background-color: lightgray;
margin-right: 1px;
text-align: center;
width: 30px;
}
Để biết thêm thông tin, hãy xem tại https://www.w3schools.com/cssref/sel_id.asp
