简体   繁体   English

在模板文字中设置 div 样式?

[英]style a div inside a template literal?

i have this api data coming from a server and i wanna dynamically render the data based on each response.我有来自服务器的这个api data ,我想根据每个响应动态呈现数据。 problem occurs when i am trying to change the style of the div当我尝试更改 div 的样式时出现问题

say i have this div container with 4 child element说我有这个带有4 child element div 容器

 <div class ='parent'> <div id = 'child_1'></div> <div id = 'child_2'></div> <div id = 'child_3'></div> <div id = 'child_4'></div> </div>

here is the css这是css

 body { padding: 2em; display: grid; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 1fr); grid-gap: 1em; grid-auto-rows: minmax(395px, auto); height: 100vh; } .grand_parent { width: 15em; height: 15em; border: 1px solid black; display: flex; justify-content: center; align-items: center; } .parent { width: 10em; height: 10em; border: 2px solid black; /* display: flex; justify-content: center; align-items: center; flex-direction: column; */ position: relative; } .parent > div { background-color: green; width: 2em; height: 2.3em; border: 1px solid black; }

Here is the js with just one chunk of data这是只有一大块数据的js

 const data = [59.18, 70.39, 77.8, 60.43, 57.09, 53.59, 47.66, 61.3, 47.64, 55.45, 43.57, 72.31, 54.03, 63.32, 52.37, 45.14, 53.2, 48.16, 51.13, 45.34]; const dataOne = data[1]; console.log(data); // childOne.style.width = '60%'; const markup = data.map(el =>{ return ` <div class = 'grand_parent'> <div class ='parent'> <div id = 'child_1' style='width:${el};'></div> <div id = 'child_2'></div> <div id = 'child_3'></div> <div id = 'child_4'></div> </div> </div> ` } ) document.body.insertAdjacentHTML('afterbegin',markup);

i have been trying as much techniques as i have in my newbie vault,here are the ones so far我一直在尝试与我在新手保险库中一样多的技术,这是迄今为止的技术

 let childOne = document.getElementById('child_1'); childOne.style.width= `${data}%`;

if i do this nothing happens :S如果我这样做,什么都不会发生:S

another one to check -另一个要检查 -

 let childOne = document.getElementById('child_1'); childOne.style.width= `${dataOne}%`; //This only applies to the first div and rests have no idea about this code

I am trying to do this with just pure vanilla Js here.any other ways to render such progress bar is highly appreciated.我试图在这里只用纯香草 Js来做到这一点。高度赞赏任何其他呈现这种进度条的方法。 :) :)

Well,basically i could put this as an inline styling like this..嗯,基本上我可以把它作为这样的内联样式..

<div id = 'child_1' style='width:${el}%;'></div>

This one silly missed unit symbol took 2 days out of my project.这个愚蠢的单位符号在我的项目中花费了 2 天时间。 but feels good as i was able to learn a great deal trying to figure out things own my own.但感觉很好,因为我能够学到很多东西,试图找出属于我自己的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM