【问题标题】:How to add svg in html, using JavaScript DOM?如何使用 JavaScript DOM 在 html 中添加 svg?
【发布时间】:2019-07-01 09:05:28
【问题描述】:

我想通过 DOM 操作添加 svg 图像,而不是在 HTML DIV 中添加它们?

我已经通过谷歌搜索尝试了所有方法,但找不到更好的解决方案。 我想在 span 元素中插入 svg 图像(assets/close.svg)而不是“X”。这是在'studentDetails' Div 里面。将感谢您的帮助。

HTML:

<div id="studentDetails" class="hidden"></div>

javascript:

var studentDetails = document.getElementById('studentDetails');
var favouriteStudent = 
    contacts[parseInt(e.currentTarget.id)].favourite ? 'favourite' : '';
studentDetails.innerHTML =
    "<span id='close-details'>x</span>" +
    "<span id='favourite' class='" +
    favouriteStudent +
    "'>*</span>" +
    '<div>' +
    contacts[parseInt(e.currentTarget.id)].name +
    '</div>' +
    '<div>' +
    contacts[parseInt(e.currentTarget.id)].email +
    '</div>';
studentDetails.setAttribute('class', 'hidden');

CSS:

#close-details {
    display: block;
    float: right;
    font-size: 20px;
    margin-top: -8px;
    background-image: url('assets/close.svg');
    background-repeat: no-repeat;
    background-position: right;
}

【问题讨论】:

标签: javascript html css dom svg


【解决方案1】:

这可能会有所帮助,因为您可以使用 IMG 标签简单地添加 svg:

var studentDetails = document.getElementById('studentDetails');
var favouriteStudent = 
  contacts[parseInt(e.currentTarget.id)].favourite ? 'favourite' : '';
  studentDetails.innerHTML =
  "<span id='close-details'><img src='assets/close.svg'></span>" +
  "<span id='favourite' class='" +
  favouriteStudent +
  "'>*</span>" +
  '<div>' +
  contacts[parseInt(e.currentTarget.id)].name +
  '</div>' +
  '<div>' +
  contacts[parseInt(e.currentTarget.id)].email +
  '</div>';

我已在第 5 行进行了编辑,正如您所见,我将 X 替换为图像标签..

【讨论】:

  • 我希望它有所帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 2013-07-08
相关资源
最近更新 更多