【问题标题】:How to dynamically change the "width" of a style in HTML template used in a NodeJs express app如何在 NodeJs express 应用程序中使用的 HTML 模板中动态更改样式的“宽度”
【发布时间】:2019-05-08 03:55:20
【问题描述】:

我正在尝试动态设置<div> 的宽度值,该<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% 我希望看到彩色条 &lt;div&gt; 仅填充了 20%,并且上面也写有百分比。 就目前而言,我可以将百分比写入条形图,但它只是用颜色填充整个条形图。

【问题讨论】:

    标签: html css node.js express


    【解决方案1】:

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

    您可以在 JS 文件中更新 &lt;div&gt; 的大小: 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 示例。希望对您有所帮助。

    【讨论】:

    • 嗨,不幸的是,我似乎无法在 HTML 中运行任何类型的 JS 脚本来进行这些更改。 HTML 从未实际运行,仅用作:var templateHtml = fs.readFileSync(HTML-FILE, 'utf8');,如果不清楚,请见谅
    • 如果您构建 HTML 页面,您可以将 Javascript 和 CSS 块插入其中。复制过去 &lt;script&gt; ... Your JS code ... &lt;/script&gt; 之间的 js 脚本。 CSS 样式也是如此: 。不确定答案?
    • 我自己并没有构建 HTML 模板,但是您的评论确实帮助我以不同的方式思考这个问题并让我找到了解决方案。在我的 JS 中创建
      并使用 template.replace 将其引入 HTML,所以谢谢你
    • 很高兴为您提供帮助。随意接受答案:)
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签