javascript - 在 HTML 中选择图像

标签 javascript html

我有一个图像网格,它以 HTML 的形式从 PHP 函数中输出。这些图像目前有一个 onclick() 函数,可以将链接到图像的值添加到通用值中。 EG:universalInt += imageInt;

我想做的是,当图像被点击时,有某种变量显示图像被选中,而当它被再次点击时,它又被取消选中。我想要这个,所以 onclick() 函数可以像这样工作:

    if(selected){ 
    universalInt += imageInt;
    //append item to array
} 
    else if (!selected){ 
    universalInt -= imageInt; 
    //remove item from array
}

我一直在四处寻找,但找不到任何东西,是否有一种简单的方法可以将类似“选定”的变量添加到 HTML 图像中?我不想使用附加组件。

最佳答案

我建议采用以下方法:

function select(opts) {

  // caching the clicked element for later (repeated) use:    
  var clicked = this,

  // setting the default settings:
    defaults = {
      'element': 'img',
      'selectedAttribute': 'data-selected',
      'markParent': true,
      'parentAttribute': 'data-childSelected',
      'parentMarker': '✓'
    };

  // finding the currently-selected elements (if any) and, if
  // any are found, converting that NodeList to an Array,
  // otherwise using an empty array:    
  var selected = Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0).length ? Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0) : [];

  // discovering whether the clicked element is already
  // in the array (if it's already selected):
  isSelected = selected.indexOf(clicked) > -1;

  // if it's in the array already, we want to de-select:
  if (isSelected) {

    // we de-select by removing the relevant attribute:
    clicked.removeAttribute(defaults.selectedAttribute);

    // if the settings indicate that the parent is also
    // marked:
    if (defaults.markParent === true) {

      // we remove the parent's 'marking' attribute also:
      clicked.parentNode.removeAttribute(defaults.parentAttribute);
    }
  } else {

    // otherwise we set the 'marking' attribute on the 
    // clicked element (to true), and:
    clicked.setAttribute(defaults.selectedAttribute, true);

    // if we're to mark the parent also:
    if (defaults.markParent === true) {

      // we set the parent-marking attribute to the string
      // held in the given variable, for use in the CSS (later):
      clicked.parentNode.setAttribute(defaults.parentAttribute, defaults.parentMarker);
    }
  }

  // here we return the (new) NodeList of selected elements:
  return document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']');
}

// converting the NodeList of <img> elements to an array:    
var images = Array.prototype.slice.call(document.querySelectorAll('img'), 0);

// iterating over that array with Array.prototype.forEach(),
// the first argument to forEach() (here: 'img') is the
// current array-element of the array over we're iterating:
images.forEach(function(img) {

  // binding the select() function to handle the 'click' event
  // on the given element-node:
  img.addEventListener('click', select);
});

function select(opts) {

  var clicked = this,
    defaults = {
      'element': 'img',
      'selectedAttribute': 'data-selected',
      'markParent': true,
      'parentAttribute': 'data-childSelected',
      'parentMarker': '✓'
    };

  var selected = Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0).length ? Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0) : [];
  isSelected = selected.indexOf(clicked) > -1;

  if (isSelected) {
    clicked.removeAttribute(defaults.selectedAttribute);
    if (defaults.markParent === true) {
      clicked.parentNode.removeAttribute(defaults.parentAttribute);
    }
  } else {
    clicked.setAttribute(defaults.selectedAttribute, true);
    if (defaults.markParent === true) {
      clicked.parentNode.setAttribute(defaults.parentAttribute, defaults.parentMarker);
    }
  }

  return document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']');
}

var images = Array.prototype.slice.call(document.querySelectorAll('img'), 0);

images.forEach(function(img) {
  img.addEventListener('click', select);
});
ul,
li {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
li {
  height: 100px;
  width: 100px;
  display: inline-block;
  position: relative;
}
li[data-childSelected]::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 5px solid rgba(255, 190, 0, 0.5);
  pointer-events: none;
}
li[data-childSelected]::after {
  content: attr(data-childSelected);
  position: absolute;
  top: 5px;
  right: 5px;
  width: 2em;
  height: 2em;
  background-color: rgba(255, 190, 0, 0.5);
  border-radius: 0 0 0 1em;
  color: #fff;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 0 4px #000;
  line-height: 2em;
}
#selected::before {
  content: 'Selected images: '
}
#selected:empty::before {
  content: '';
}
<div id="selected"></div>
<ul>
  <li>
    <img src="http://lorempixel.com/100/100/people/1" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/2" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/3" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/4" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/5" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/6" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/7" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/8" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/9" />
  </li>
</ul>

外部 JS Fiddle demo , 用于实验。

或者,要使用返回的 NodeList,我们可以通过以下方式调用完全相同的函数(为简洁起见,此处省略了未更改的函数,但它位于代码段和外部 Fiddle 中):

images.forEach(function(img) {
  img.addEventListener('click', function() {

    // setting the textContent of the selected Node
    // to the length of the returned NodeList:
    document.getElementById('selected').textContent = select.apply(img).length;
    // above we use Function.prototype.apply() to
    // explicitly set the select() function's 'this'
  });
});

function select(opts) {

  var clicked = this,
    defaults = {
      'element': 'img',
      'selectedAttribute': 'data-selected',
      'markParent': true,
      'parentAttribute': 'data-childSelected',
      'parentMarker': '✓'
    };

  var selected = Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0).length ? Array.prototype.slice.call(document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']'), 0) : [];
  isSelected = selected.indexOf(clicked) > -1;

  if (isSelected) {
    clicked.removeAttribute(defaults.selectedAttribute);
    if (defaults.markParent === true) {
      clicked.parentNode.removeAttribute(defaults.parentAttribute);
    }
  } else {
    clicked.setAttribute(defaults.selectedAttribute, true);
    if (defaults.markParent === true) {
      clicked.parentNode.setAttribute(defaults.parentAttribute, defaults.parentMarker);
    }
  }

  return document.querySelectorAll(defaults.element + '[' + defaults.selectedAttribute + ']');
}

var images = Array.prototype.slice.call(document.querySelectorAll('img'), 0);

images.forEach(function(img) {
  img.addEventListener('click', function(e) {
    document.getElementById('selected').textContent = select.apply(img).length;
  });
});
ul,
li {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
li {
  height: 100px;
  width: 100px;
  display: inline-block;
  position: relative;
}
li[data-childSelected]::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 5px solid rgba(255, 190, 0, 0.5);
  pointer-events: none;
}
li[data-childSelected]::after {
  content: attr(data-childSelected);
  position: absolute;
  top: 5px;
  right: 5px;
  width: 2em;
  height: 2em;
  background-color: rgba(255, 190, 0, 0.5);
  border-radius: 0 0 0 1em;
  color: #fff;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 0 4px #000;
  line-height: 2em;
}
#selected::before {
  content: 'Selected images: '
}
#selected:empty::before {
  content: '';
}
<div id="selected"></div>
<ul>
  <li>
    <img src="http://lorempixel.com/100/100/people/1" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/2" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/3" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/4" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/5" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/6" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/7" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/8" />
  </li>
  <li>
    <img src="http://lorempixel.com/100/100/people/9" />
  </li>
</ul>

外部 JS Fiddle demo , 用于实验。

引用资料:

关于javascript - 在 HTML 中选择图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30436167/

相关文章:

javascript - Jquery Mouseenter触发父元素

javascript - YUI 中的 onChange

javascript - 有效的隐藏和表演类(class)

javascript - 如何使 Javascript 中的函数成为我的 html 的全局函数

javascript - 网页未调整大小 - 代码中没有约束

javascript - Chrome 中奇怪的 js 对象的字段行为

javascript - 如何在 d3 强制布局中附加文本?

html - CSS 中的半透明边框 - Tumblr 主题编码

html - float 在 flex 容器中不起作用

javascript - 在 ASP.NET MVC 中使用路由 URL 构建导航