javascript - 通过 Onclick 使用 appendChild/replaceChild 函数切换图像堆栈

标签 javascript html css appendchild removechild

大家好,我想通过 onclick 函数切换图像堆栈集。这里的问题是 appendchild 总是会添加一个新的图像堆栈,而不是替换原来的图像堆栈。

我试过replacechild(),但是显然全局变量和函数不能被局部变量和函数影响。有没有更好的方法来实现开关功能?

在下面添加了一个简单的演示,

// how to use the funciton on line 94
// for questions email felix@demont.is

var images10 = [
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"

];

var imagesbone = [
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];

var imageslung = [
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
  "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];

function ImageStack(options) {

  var self = this;

  self.img_array = options.images;

  self.stack = document.createElement('div');
  self.stack.style.overflow = 'auto';
  self.stack.style.maxWidth = '100%';
  self.stack.style.height = options.height;
  self.stack.style.width = options.width;
  self.stack.style.backgroundSize = 'cover'
  self.stack.style.position = 'relative';

  var typeRegex = /(\D+)/
  var sizeType = options.height.match(typeRegex)[0]

  var numberRegex = /(\d+)/
  self.height_number = Number(options.height.match(numberRegex)[0])

  self.wrapper = document.createElement('div');

  for (var i = 0; i < self.img_array.length; i++) {

    var image = document.createElement('img');
    image.src = self.img_array[i];

    image.style.display = 'none';
    image.style.position = 'absolute';
    image.style.width = options.width;
    image.style.height = options.height;
    image.style.top = 0;
    image.style.left = 0;
    image.dataset.iid = i;

    self.wrapper.appendChild(image);

  }

  self.image_elements = self.wrapper.querySelectorAll('img');

  self.scrollobject = document.createElement('div');
  self.scrollobject.style.width = '100%';
  self.scrollobject.style.position = 'absolute';
  self.scrollobject.style.zIndex = '2';
  self.img_count = (self.img_array.length > 15) ? self.img_array.length : 15;
  self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

  self.scrollobject.style.height = self.scrollobject_height + sizeType;

  self.scrollUpdate = function(e) {

    self.height_number = self.stack.getBoundingClientRect().height
    self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

    var sT = self.stack.scrollTop
    var hn05 = self.img_array.length - 1
    var hh = (self.scrollobject_height - self.height_number) / hn05
    scrollval = Math.floor(sT / (hh))

    self.currentimg = self.image_elements[scrollval].src

    self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';

  }

  self.stack.addEventListener('scroll', self.scrollUpdate);

  self.currentimg = self.image_elements[0].src
  self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';



  window.addEventListener('resize', function() {
    var stackRect = self.stack.getBoundingClientRect()

    console.log(stackRect)

    self.height_number = stackRect.height
    self.scrollobject_height = Math.floor(0.1 * self.img_array.length * self.height_number);

    self.stack.style.width = stackRect.width + 'px'
    self.stack.style.eight = stackRect.width + 'px'
  })



  self.stack.appendChild(self.wrapper);
  self.stack.appendChild(self.scrollobject);

  return self.stack;

}

/*problems here*/
/*global var*/
var images = images10;

/*local var*/
function softtissue(){
	var images= images10;
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);
}

function bone(){
var images= imagesbone;
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);	
}
function lung(){
var images= imageslung;
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);

}


/*how to switch the local var in global function*/
var stack = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack);
<div>
  <button id="softtissue" type="button" onclick="softtissue();return false" class="button">
  Soft Tissue</button>
  <button id="bone" type="button" onclick="bone(); return false;" class="button">
	Bone</button>
  <button id="lung" type="button" onclick="lung(); return false" class="button">
	Lung</button>
</div>

<div class="example">
</div>

最佳答案

将您的图像数组声明为 map 而不是单个变量,并更改您的按钮以调用 setImageStack('bone')setImageStack('lung') 等。

setImageStack 函数中,为该 id 创建 ImageStack(如果它尚不存在),存储它以备将来引用,并将其插入到文档中。

请参阅下面的工作示例。

const stacks = {
   bone: [
      // list of bone images
   ],
   softTissue: [
      // list of bone images
   ],
   lung: [
      // list of lung images
   ]
};


<button onClick="setImageStack('bone')">bone</button>
<button onClick="setImageStack('softTissue')">soft tissue</button>
<button onClick="setImageStack('lung')">lung</button>

// a map to keep track of the ImageStack instances
const imageStacks = {};

const imagesByStackName = {
  softTissue: [
    "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
    "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
    // others omitted for this example
  ],

  bone: [
    "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG",
    "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
    // others omitted
  ],

  lung: [
    "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
    "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
  ]
};


function ImageStack(options) {

  var self = this;

  self.img_array = options.images;

  self.stack = document.createElement('div');
  self.stack.style.overflow = 'auto';
  self.stack.style.maxWidth = '100%';
  self.stack.style.height = options.height;
  self.stack.style.width = options.width;
  self.stack.style.backgroundSize = 'cover'
  self.stack.style.position = 'relative';

  var typeRegex = /(\D+)/
  var sizeType = options.height.match(typeRegex)[0]

  var numberRegex = /(\d+)/
  self.height_number = Number(options.height.match(numberRegex)[0])

  self.wrapper = document.createElement('div');

  for (var i = 0; i < self.img_array.length; i++) {

    var image = document.createElement('img');
    image.src = self.img_array[i];

    image.style.display = 'none';
    image.style.position = 'absolute';
    image.style.width = options.width;
    image.style.height = options.height;
    image.style.top = 0;
    image.style.left = 0;
    image.dataset.iid = i;

    self.wrapper.appendChild(image);

  }

  self.image_elements = self.wrapper.querySelectorAll('img');

  self.scrollobject = document.createElement('div');
  self.scrollobject.style.width = '100%';
  self.scrollobject.style.position = 'absolute';
  self.scrollobject.style.zIndex = '2';
  self.img_count = (self.img_array.length > 15) ? self.img_array.length : 15;
  self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

  self.scrollobject.style.height = self.scrollobject_height + sizeType;

  self.scrollUpdate = function(e) {

    self.height_number = self.stack.getBoundingClientRect().height
    self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);

    var sT = self.stack.scrollTop
    var hn05 = self.img_array.length - 1
    var hh = (self.scrollobject_height - self.height_number) / hn05
    scrollval = Math.floor(sT / (hh))

    self.currentimg = self.image_elements[scrollval].src

    self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';

  }

  self.stack.addEventListener('scroll', self.scrollUpdate);

  self.currentimg = self.image_elements[0].src
  self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';



  window.addEventListener('resize', function() {
    var stackRect = self.stack.getBoundingClientRect()

    console.log(stackRect)

    self.height_number = stackRect.height
    self.scrollobject_height = Math.floor(0.1 * self.img_array.length * self.height_number);

    self.stack.style.width = stackRect.width + 'px'
    self.stack.style.eight = stackRect.width + 'px'
  })



  self.stack.appendChild(self.wrapper);
  self.stack.appendChild(self.scrollobject);

}

// keep track of instantiated ImageStacks
const stacks = {};

// creates a stack for the specified image list and stores it in the cache map
function createStack(whichImages) {
  const images = imagesByStackName[whichImages];
  stacks[whichImages] = new ImageStack({
    images,
    width: '512px',
    height: '512px'
  });
  return stacks[whichImages];
}

// button onclick handler
function setImageStack(whichImages) {
  // get the ImageStack instance for this set from our map cache; create it if it's not already there.
  const stack = stacks[whichImages] || createStack(whichImages);

  const container = document.querySelector('.example');
  const child = container.firstElementChild;

  if (child) {
    container.replaceChild(stack.stack, child);
  } else {
    container.appendChild(stack.stack);
  }
}

// set up initial stack display
setImageStack(Object.keys(imagesByStackName)[0]);
<div>
  <button onclick="setImageStack('softTissue')" class="button">
      Soft Tissue</button>
  <button onclick="setImageStack('bone')" class="button">
    	Bone</button>
  <button onclick="setImageStack('lung')" class="button">
    	Lung</button>
</div>

<div class="example">
</div>

关于javascript - 通过 Onclick 使用 appendChild/replaceChild 函数切换图像堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56179147/

相关文章:

javascript - 在javascript中的类定义中添加原型(prototype)

javascript 我可以动态构建一个函数名来调用吗?

javascript - 单击取消按钮后清除选中的复选框

css - onmouseover 事件不适用于移动设备

html - 由于高度不同,多个 div 之间存在一些随机空白区域。如何在不使用强制高度的情况下摆脱它们?

javascript - 将嵌套数组合并为一个?

javascript - JSTL。如何从 c 中的 &lt;script&gt; 调用函数 :set jSTL tag?

java - 使用 JS 以编程方式向 BIRT 中的表添加排序条件

python - 在 html Flask 中迭代嵌套字典时出现 jinja2.exceptions.UndefinedError

html - TextMate:突出显示插入位置的匹配标签