内联样式在替换图元时会导致问题

Inline styles causing problems when replacing an element

本文关键字:问题 图元 样式 替换      更新时间:2023-09-26

我正在处理的脚本出现问题,该脚本从API获取相同的HTML元素并每20秒更新一次。我有一些脚本可以监视数据属性的变化,如果检测到变化,就会将其动画化到视图中。

我遇到的问题是在酒吧第一次出现后保持它的一致性。如果我将display: none内联属性添加到元素中,或者如果我在页面加载时使用jQuery隐藏元素,脚本会重写该元素,从而导致它再次消失。

这是HTML元素:

<aside id="alert" class="row" style="display: none" data-supressed="false" data-path="path_here">
</aisde>

这就是Javascript的样子:

  function reloadBar() {
  /* Fires every 20 seconds. */
    var $alert = $("#alert");
    var path = $alert.data('path');
    /* Performs an AJAX call on the feature path. */
    $.ajax ({
      url: path + secondary-path,
      success: function(data) {
        /* If successful it will replace the bar with the new bar. */
        /* Grabs the updated element from the API */
        var newBar = $($.parseHTML(data.rendering)).find('#alert');
        var newBarHtml = newBar[0].outerHTML;
        var currBarSupp = $alert.data('supressed');
        var newBarSupp = newBar.data('supressed');
        /* If the new bar is supressed and old one is not, hide it. */
        if (!currBarSupp && newBarSupp) {
          $alert.animate({height:0});
          $alert.parent().animate({height:0}, function() {
            $(this).hide()
          });
        }
        else {
          /* Replaces the element */
          $alert.replaceWith(newBarHtml);
          /* If the new bar is not supressed, update it and animate it into view. */
          if (!newBarSupp) {
          updateBar(true);
          }
      }
    }
  })
};

updateBar()将触发哪个动画进入视图:

function updateBar(isReload) {
    var $alert = $("#alert");
    if (isReload === true) {
      $alert.css("display","block")
      $alert.animate({height:"45px"});
      $alert.parent().animate({height:"45px"}, function() {
        $(this).hide().show("slow");
      });
    }
  }

20秒后,reloadBar脚本将再次启动,并将display: none属性返回到side元素,这将导致它在不应该出现的时候消失。

有没有一种更一致的方法可以在元素上保持该属性?任何向元素添加任何类型的内联样式/类的行为都会导致它出现问题。我发现,即使我在脚本最初启动时尝试使用.hide(),它仍然会替换元素并删除display: none,所以问题会双向发生。

有什么建议吗?

我通过在HTML元素上使用字符串切片并将CSS元素修补到它上来解决了这个问题。首先,我使用var currStyles = $alert.attr("style"); 保存了当前元素的样式属性

之后,我拆分了通过API提供的更新元素的字符串,并将内联样式添加到其中。我将其分配给一个名为updatedBar:的新变量

var updatedBar = newBarHtml.slice(0,6) + ' style="' + currStyles + '"' + newBarHtml.slice(6);

然后我用updatedBar变量替换了页面上的那个元素。

$alert.replaceWith(updatedBar);

脚本现在在从页面中获取新元素后保持内联样式的一致性,因此jQuery hide()和show()现在可以按预期工作。