zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

DOM基础测试46期 #72

Open zhangxinxu opened 4 years ago

zhangxinxu commented 4 years ago

已知HTML如下:

<img src="1.jpg" width="130rem">

此时图片宽度是130px,设置的单位rem被忽略了。请实现图片的width属性值如果有单位,则按照单位宽度渲染。


大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式。

```js
// 你的JS代码写在这里
 ```

其他 本期小测没有直播,也没有打分,但是会反馈要点。

XboxYan commented 4 years ago
<img src="1.jpg" width="130rem" is="x-img">
class XImg extends HTMLImageElement {

    static get observedAttributes() {return ['width']; }

    constructor() {
        super();
    }

    get width() {
        return this.getAttribute('width');
    }

    connectedCallback() {
        this.render();
    }

    render(){
        this.style.width = this.width;
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if(name === 'width'){
            this.render();
        }
    }
}

customElements.define('x-img', XImg, { extends: 'img' });
livetune commented 4 years ago
function setWidth(elm) {
  const width = elm.getAttribute('width')
  if (width.match(/^\d+(\w+|%)$/)) {
    elm.style.width = width
  }
}
Array.from(document.getElementsByTagName('img')).forEach(elm => {
  setWidth(elm)
})
zy017 commented 4 years ago
function formatImgWidth() {
   var imgList = document.querySelectorAll('img')
   imgList.forEach(item => {
     var w = item.getAttribute('width')
     if(/^[0-9]+([a-zA-z]+|%)$/.test(w)) {
       item.style.width = w
     }
   })
}

formatImgWidth()
zer0fire commented 4 years ago
function resizeImg() {
  var imgList = document.querySelectorAll('img')
  imgList.forEach(img => {
    if(img.attributes.width.value) {
      img.style.width = img.attributes.width.value
    }
  })
}
resizeImg()
xxf1996 commented 4 years ago

我觉得要点应该是document.images和使用getAttribute()方法获取width属性值?

demo

<img src="https://placekitten.com/500/300" width="30rem">
function checkImageWidth () {
  Array.from(document.images).forEach(img => {
    const widthVal = img.getAttribute('width')
    img.style.width = widthVal
  })
}

checkImageWidth()
liyongleihf2006 commented 4 years ago
<div>
  <img src="100.png" width="100rem" />
</div>
<img src="100.png" width="100rem" />
<div id="abc"></div>
Array.from(document.images).forEach(function (image) {
  var widthAttr = image.getAttribute('width')
  if (isNaN(widthAttr)) {
    image.style.width = widthAttr
  }
})
var targetNode = document.body;
var observerOptions = {
  childList: true,  // 观察目标子节点的变化,是否有添加或者删除
  attributes: true, // 观察属性变动
  subtree: true     // 观察后代节点,默认为 false
}
function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    switch (mutation.type) {
      case 'childList':
        var nodes = Array.from(mutation.addedNodes)
        nodes.filter(function (node) {
          return node.tagName === 'IMG'
        }).forEach(function (img) {
          var widthAttr = img.getAttribute('width')
          if (isNaN(widthAttr)) {
            img.style.width = widthAttr
          }
        })
        break;
      case 'attributes':
        // 设置属性的监听似乎是多余的,因为通过el.width='100rem'来设置的时候因为是非法值,所以每次都是设置成0
        var target = mutation.target
        if (target.tagName === 'IMG') {
          var img = target
          var attr = mutation.attributeName
          if (attr === 'width') {
            var widthAttr = img.getAttribute('width')
            if (isNaN(widthAttr)) {
              img.style.width = widthAttr
            }
          }
        }
        break;
    }
  });
}
var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
var abc = document.querySelector("#abc")
abc.innerHTML = `<img id="def" width="100rem" />`
ziven27 commented 4 years ago
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
    var img = imgs[i];
    var attrWidth = img.getAttribute('width');
    if (isNaN(attrWidth)) {
        img.style.width = attrWidth;
    }
}