【问题标题】:How to put params from database table into CSS style如何将数据库表中的参数放入 CSS 样式中
【发布时间】:2015-12-08 22:31:19
【问题描述】:

我想在数据库表 (MySQL) 中定义 CSS 样式的参数,并将它们用于例如样式链接菜单。我知道如果我们将变量放入这样的样式中是可能的:

<div id="content-inner" style="<?php echo $this->var['color'] ;?>">

但也许有人知道更好的方法?

【问题讨论】:

  • imo 您建议的方式是一种好方法,另一种方法是通过 php 生成整个 css 文件(加载 style.css.php 或类似的东西)。但这几乎是一样的。不过可能更干净
  • 问题是直接在 html 行中设置样式是否是一种好方法?
  • 你不应该使用数据库(MySQL)来执行这样的任务......这会在你的网络服务器和数据库服务器上造成不必要的负载,只会消耗更多的内存没原因。您应该使用 JavaScript 和包含这些值的静态声明的 JSON 对象。如果您对我的意思感到困惑,请告诉我,我会发布一个示例。

标签: php html mysql css


【解决方案1】:

而不是写

<?php echo $this->var['color'] ;?>

你可以写

<?= $this->var['color'] ?>

为了更精简、更快、更简洁和更易阅读的代码

【讨论】:

    【解决方案2】:

    在你的主页使用

    <style type="text/css">
    .custom_class_name{
    <?php echo $this->var['color'] ;?>
    }
    </style>
    

    然后在当前页面中随意使用这个 custom_class_name。

    【讨论】:

      【解决方案3】:

      您应该使用 JavaScript 来执行这样的任务,使用数据库只会在您的 Web/数据库服务器上创建不必要的负载,从而占用您的内存。

      如果它是一个单一的属性,你应该像这样更新:

      //单个 CSS 更改

      <!DOCTYPE html>
      <html>
      <head>
      <style>
      .body{
          margin: 0 !important;
      }
      #target{
          height: 100px;
          width: 100px;
          background: red;    
      }
      </style>
      <script>
      function colorChange(){
          var target = document.getElementById("target"); 
          target.setAttribute("style", "background:blue;");
      }
      </script>
      </head>
      <body>
          <button onclick="colorChange();">Click Me</button>
          <div id="target"></div>
      </body>
      </html> 
      

      如果是多个属性更改,您应该像这样使用 id/class:

      //多个CSS更改

      <!DOCTYPE html>
      <html>
      <head>
      <style>
      .body{
          margin: 0 !important;
      }
      #target1{
          height: 100px;
          width: 100px;
          background: red;    
      }
      #target2{
          height: 200px;
          width: 300px;
          background: blue;   
      }
      </style>
      <script>
      function colorChange(){
          var target = document.getElementById("target1");    
          target.setAttribute("id", "target2");
      }
      </script>
      </head>
      <body>
          <button onclick="colorChange();">Click Me</button>
          <div id="target1"></div>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2016-11-28
        • 2014-05-08
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 2021-12-29
        相关资源
        最近更新 更多