首页 > 解决方案 > 在 css 类中使用 Javascript 图像路径

问题描述

背景

网站中,我显示蒙版图像路径如下:

<script>
var cardConfig = { "pages": [{ "name": "/images/invitations/birthday/ice1.png", }], }
</script>

我允许用户在掩码图像中上传图像....

用户上传图像后,我将在掩码图像中填充用户上传的图像:

1.面具图像

在此处输入图像描述

2.用户上传图片

在此处输入图像描述

3.用户上传的面具上的图像[最终图像]:

在此处输入图像描述

代码笔: https ://codepen.io/kidsdial2/pen/OdyemQ

JSfiddle:http: //jsfiddle.net/2xq8p0zy/

html

<body>
  <img src="http://139.59.24.243/images/invitations/birthday/a.jpg" alt="">
</body>

css

body {
  background-color: #111;
  color: #555;
  font-size: 1.1em;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

img {
  margin: 20px auto;
  display: block;
  width: 100%;
  height: 500px;
  -webkit-mask-image: url(http://139.59.24.243/images/invitations/birthday/ice.png);
  mask-image: url(http://tympanus.net/codrops-playground/assets/images/cssref/properties/mask-image/mask-image.png);
  -webkit-mask-position: center center;
  mask-position: center center;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

要求

这里要在遮罩图像中填充上传的图像,我使用下面的 css 代码来显示遮罩图像....但是在这个过程中我想使用 html 代码遮罩图像而不是使用 css 代码遮罩图像......

css 掩码图像代码

-webkit-mask-image: url(http://139.59.24.243/images/invitations/birthday/ice.png);

Html 掩码图像代码

<script>
    var cardConfig = { "pages": [{ "name": "/images/invitations/birthday/ice1.png", }], }
    </script>

标签: javascripthtmlcss

解决方案


您将不得不在您的 js 中以编程方式更改样式。像这样:

const targetDiv = document.getElementById('target')

function changeColorTo(hex) {
  // you can change single attributes like this
  targetDiv.style.backgroundColor = hex
  
  // alternatively you can override all of the local styles like this
  targetDiv.setAttribute('style', `background-color:${hex};`)
  // or
  targetDiv.style.cssText = `background-color:${hex};`
}
#target {
  width: 5rem;
  height: 5rem;
  border: 1px solid black;
}
<div id="target"></div>
<button onclick="changeColorTo('#00f')">Change to Blue</button>
<button onclick="changeColorTo('#0f0')">Change to Green</button>
<button onclick="changeColorTo('#f00')">Change to Red</button>

同样的方法,你可以改变掩码:

target.style.webkitMaskImage = 'url(https://…)'
target.style.maskImage = 'url(https://…)'

推荐阅读