加载 ajax 响应(html 内容数据)而不发生 css 冲突

Load ajax response (html content data) without css conflict

本文关键字:冲突 css 数据 响应 ajax html 加载      更新时间:2023-09-26

1) 我有 2 个不同的域 i) www.xxx.xom ii) www.yyy.com

2)然后通过ajax将服务器调用从xxx页面发送到yyy页面

3)从YYY获取HTML内容到XXX页面(内容包含带有内联CSS的HTML数据)

4)现在我想将响应(html内容)附加到我的DOM中,但没有css冲突(这意味着响应内容不受父css的影响)

注意:是否可以在没有 IFRAME 的情况下渲染

示例代码:

document.onreadystatechange = function () {
  if (document.readyState == "interactive") {
    var ajax_response = "<div style='color: blue;'>I m blue </div>"; // sample server reponse
    document.getElementById("child").innerHTML = ajax_response;
  }
}
#parent div {
  color: red !important;
}
<div id="parent">
  <div>I m red</div>
  <div id="child"></div>
  <div>I m red too</div>
</div>

输出:红色将应用于"我是蓝色"文本(因为"!important"标签)

如果我理解正确,你想设置第一个div的样式,而不是第二个div,它来自你的ajax调用。

#parent:first-child {
  color: red !important;
}

这只会影响您的div 的第一个div #parent

我得到了这个工作:https://jsfiddle.net/Twisty/sc6n560t/

.HTML

<a id="act" href="">Action</a>
<div id="parent">
  <div>I'm red</div>
  <div id="child"></div>
  <div>Other Text</div>
</div>

.CSS

#parent div {
  color: red;
}
div#child.content {
  all: default;
}

简讯

$(document).ready(function() {
  $("#act").click(function(e) {
    e.preventDefault();
    var ajax_response = "<div style='color: blue;'>I'm blue </div>"; // sample server reponse
    $("#child").html(ajax_response);
  });
});

此答案是在此问题的更新中找到的:防止子元素继承父样式的 CSS

编辑:CSS工作组正在做一些事情:

div.content { all: default; }

不知道浏览器何时或是否会实现这一点。

编辑2:截至2015年3月,除Safari和IE/Edge之外的所有现代浏览器 已经实现了它: https://twitter.com/LeaVerou/status/577390241763467264(谢谢,@Lea 维鲁!

xxx页面中创建一个div。将此添加到您的脚本中。

$("#your_div_id").append(response_from_server)