为通过 JavaScript 创建的按钮使用自定义背景

问题描述 投票:0回答:1

尝试在 JavaScript 中创建一个按钮来使用特定 API 图像的背景图像 我看到很多使用

.style.backgroundImage = 'Url("yourimagelink")';
的建议。但似乎无法弄清楚。

    let button = document.createElement('button');
    button.classList.add('btn-image');
    button.innerText = item.name;
    button.style.backgroundImage = item.imageUrl;

没有出现图像,也没有错误。

javascript image button styles imagebutton
1个回答
0
投票

您应该将按钮添加到 DOM,例如使用 appendChildcreateElement 只创建按钮实例,不会将其添加到 DOM。

工作示例如下:

item = { name: 'test', imageUrl: 'https://images.unsplash.com/profile-1446404465118-3a53b909cc82?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=a2f8c40e39b8dfee1534eb32acfa6bc7' };

let button = document.createElement('button'); // It only create the button instance, but don't add it to the DOM
document.body.appendChild(button); // You should add the button to the DOM
button.classList.add('btn-image');
button.innerText = item.name;
button.style.backgroundImage = `url(${item.imageUrl})`;
<html>
<body>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.