gpt4 book ai didi

html - 强制 [innerHTML] 内容适应 div 宽度

转载 作者:行者123 更新时间:2023-11-27 23:29:15 26 4
gpt4 key购买 nike

我 amm 使用 angular 7,我正在尝试渲染从外部数据库 (MySQL) 获得的一些 html。我正在使用一个 div 并在这个 div 上使用 [innerHTML] 呈现 html。问题是呈现的 html 超出了 div 的宽度。 html 只能包含文本,但也可以包含图像、表格和表格内的图像。

从数据库接收到 html 后,我运行此函数。

this.sanitizer.bypassSecurityTrustHtml(html);

我已经尝试将 word-wrap:break-word 放在 css 中,但问题仍然存在。

出于测试目的,我将来自数据库的带有 html 的字符串更改为带有 src 的简单 img 标记,指向来自网络的图像,并且图像以其实际大小呈现,也不适合 div。

这就是我现在拥有的。

<div class="bloghtml" [innerHTML]="post.html_post"></div>
.bloghtml {
display: inline-flex;
max-width: 1300px;
}

所以我需要强制调整 innerHTML(包括调整图像大小)以适应 div。有没有办法做到这一点?

最佳答案

Angular 将 innerHtml 的内容放在影子 DOM 中,因此您将无法像那样对其应用样式。有一些解决方法,首先是使用::ng-deep,正如 Angular docs 中提到的那样,它已被弃用。上面写着

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools

如果你稍微改变你的代码

HTML

<div [innerHTML]="html_post"></div>

JS

html_post = '<div class="bloghtml"><img src="https://via.placeholder.com/150" /></div>'

CSS

:host ::ng-deep .bloghtml { 
display: inline-flex;
max-width: 100px;
overflow-wrap: break-word;
word-wrap: break-word;
}

:host ::ng-deep .bloghtml img {
max-width: 100px;
}

现在您可以随意设置样式。这是一个stack blitz在行动中证明这一点。

关于html - 强制 [innerHTML] 内容适应 div 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57572943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com