【问题标题】:Overwriting an element.style attribute for an image [closed]覆盖图像的 element.style 属性 [关闭]
【发布时间】:2020-06-19 02:59:29
【问题描述】:

我正在使用这个<div class="wk_seller_store_logo" data-productid ="{{product.id}}"></div>

插入链接回配置文件的图像,我相信 element.style 将图像大小控制在 50 像素,因为我可以在检查器中更改它,但无法弄清楚如何覆盖 java 脚本或 CSS。它是我可以添加到 html 的简单覆盖吗? max-height 250px !important 或类似的东西?

谢谢大家,这里是全新的!

【问题讨论】:

  • 请向我们展示更多代码。或 CSS 文件。如果你编辑你的主 css 文件或 js 文件,你会吗?
  • 欢迎来到 Stack Overflow。请浏览help for asking questions,了解如何提出一个好的问题,并在minimal,reproducible example 中使用您尝试过的方法和相关代码的详细信息更新您的问题,以便我们获得提供帮助所需的信息。跨度>
  • 感谢一直帮助我管理下面提供的解决方案,

标签: html css styles


【解决方案1】:

如果图像在您在上面<div class="wk_seller_store_logo" data-productid ="{{product.id}}"></div> 提供的 div 中呈现,那么您只需在 CSS 文件中添加以下规则即可覆盖 image 元素样式:

.wk_seller_store_logo img{
    width:250px !important;
    height:250px !important;
}

如果你想使用 js 来改变它,那么请分享为图像添加元素样式的 js 代码。

【讨论】:

  • 我不建议添加!important,因为它会覆盖元素的所有属性,这必须被视为最后一个选项。我建议 OP 调查检查元素并采取相应措施。
  • 是的,你是对的,但覆盖内联 css style 规则的唯一方法是使用 !important
  • 完美!我将此添加到 css '.wk_seller_store_logo img{ width:250px !important;高度:250px!重要;最大高度:250px !important }'
  • 我看到每个元素都在使用 !important,只有宽度和高度,没有最大高度,它扭曲了图像
  • 太好了,很高兴知道它有效。
【解决方案2】:

使用 JS,你可以使用 .dataset 从你的数据标签中检索出什么标志的信息,并使用 .style 来改变宽度......下面是一个如何实现的例子......

document.getElementsByClassName('wk_seller_store_logo');
let logo = {'wk_seller_store': 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTx3obz2G2UBHkVd-x1eTlEc_QdopClZKmeP72T1f5a5tFPqXeF&usqp=CAU'}; //<-- to illustrate getting the image from an array or object
let data = document.getElementsByClassName('wk_seller_store_logo'); //<-- Get the element that holds the dataset productid
let image = document.getElementsByClassName('image'); //<-- img tag to illustrate placing logo/img and styling logo/img
let productID = data[0].dataset['productid'];//<-- get the img source from the array or object using the dataset key value
image[0].src = logo[productID];//<-- set the value of the src attribute within the img tag to the value of the productid's key from the array 'logo' which is the `dataset['productid']` from your element
image[0].style.width = '200px';// style the image to be 200px wide `element.style`
<div class="wk_seller_store_logo" data-productid="wk_seller_store"></div>
<img class="image" src='' />

【讨论】:

  • 这个也很有用,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 2015-12-19
相关资源
最近更新 更多