html - 如何动态更改 NodeJs Express 应用程序中使用的 HTML 模板中样式的 "width"

标签 html css node.js express

我正在尝试为 <div> 动态设置宽度值在我用来生成一些 PDF 的 HTML 模板中用作彩色条。 我可以使用 {{my_value}} 之类的东西设置其他值, 但在样式中使用类似的方法似乎不起作用。

我试过使用 width: {{my_value}}% . 我还尝试通过将 div 分配给一个类来设置值,即 .divClass { "width": {{my_value}} }

HTML 模板:

<!-- Change the width dynamically to same value as {{my_value}} -->
<div style="width: 45% !important;">
<!-- Dynamic percentage below and above -->
<div style="padding-left:8px;">{{my_value}}%</div>
</div>

JS文件包含以下内容

// Get the value from the POST
var val1 = req.body.val1;

//replace the value in the template
templateHtml = templateHtml.replace('{{my_value}}', val1);

如果 POST val1 = 20%我想看到彩色条 <div>仅填充了 20%,并且上面还写有百分比。 就目前而言,我可以将百分比写到栏上,但它只是用一种颜色填充整个栏。

最佳答案

假设您的服务器回答提供百分比值:percentage .您可以从 JS 更改大小,如下所示。

您可以更新 <div> 的大小在 JS 文件中: document.getElementById("myDiv").style.width = '50px';

这是一个基本的想法:

document.getElementById("updateLoadBar").onclick = function() {
    updateLoadingBar()
};

function updateLoadingBar() {
    // Get input value
    // In your case your get this value from your template like this for example:
    // width = {{ percentage }};
    var width = document.getElementById("input-number").value;
    // Set darkBlue width
    document.getElementById("myBar").style.width = width + '%';

    // Avoiding that text overlap
    if (width >= 5) {
        // set text
        document.getElementById("text").textContent = width + "%";
    }
}
.myButton {
  border-radius: 5px;
}

#myProgress {
  width: 100%;
  height: 40px;
  margin-top: 10px;
  background-color: lightblue;
}

#myBar {
  width: 1%;
  height: 100%;
  background-color: darkblue;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
Select a number between 0 and 100:
<input id="input-number" type="number">
<input id="updateLoadBar" type="button" value="Update load bar" class="myButton">


<div id="myProgress">
  <div id="myBar">
    <div id="text">
    </div>
  </div>
</div>

您可以找到现成的示例:pure JSbootstrap例如,如果您在元素中使用 Bootstrap 。希望对您有所帮助。

关于html - 如何动态更改 NodeJs Express 应用程序中使用的 HTML 模板中样式的 "width",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026911/

相关文章:

javascript - 使用history.back时保留AJAX生成的内容

javascript - 如何设置 GAE 数据存储的 key ?

node.js - cloudinary 依赖 npm install 后找不到模块 'cloudinary' 的声明文件

html - 无法删除导航栏和横幅 css 之间的填充

javascript - 我可以在 javaScript 中使用从 Node.js 抓取的内容吗?

python - Scrapy:无法在 HTML 文档中使用 Xpath、response.css 选择内容

javascript - Jquery 导航栏无法正常工作

html - 我可以控制 IE 10 选择框的定位吗?

css - 如何在div中绝对定位?

javascript - 重置复选框选中状态从历史记录中返回