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

时间:2019-05-17 03:22:52

标签: javascript html css appendchild removechild

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

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

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

depthbins <- c(0,5,10,15,20,25,50,75,100,125,150,200,250,300,350,400)
df_i <- data.frame(latbin = c(-77.5, -78, -78.5),
                   lonbin = c(-178.5, -177.5, -176.5),
                   month = c(1,2,3),
                   Depth.m. = c(130,120,110))
do2 <- tibble(Month = c(1,2,3),
              Latitude = c(-77.5,-78,-78.5),
              Longitude = c(-178.5, -177.5, -176.5),
              "100" = c(214, 223, 345),
              "125" = c(123,234,345),
              "150" = c(345,456,567))


library(tidyverse)
# Precalculate closest bin for each row
df_i$bin = sapply(df_i$Depth.m., function(d) depthbins[which.min(abs(depthbins - d))])

# Convert do2 to long
do2_long = do2 %>%
    gather(bin, DO2, -Month, -Latitude, -Longitude) %>%
    mutate(bin = as.numeric(bin))

# Now everything can just be done as a merge
# The merge syntax would be a bit cleaner if you give the two df's
#   matching column names to start with
df_i %>%
    left_join(do2_long, by = c("month" = "Month", "latbin" = "Latitude", 
                               "lonbin" = "Longitude", "bin" = "bin"))
async addToCart(product: Product){
    let cartId = await this.getOrCreateCartId();
    let item$ = this.getItem(cartId, product.key);
    item$.snapshotChanges().pipe(take(1)).subscribe(item => {
       item$.update({ product: product, 
                      quantity: (item.payload.exportVal().quantity || 0) + 1 });
    });
}

2 个答案:

答案 0 :(得分:2)

将图像数组声明为映射而不是单个变量,并更改按钮以调用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>

答案 1 :(得分:1)

在添加新的图像堆栈之前,我通过添加一个清除所有代码的remove循环来修复它。

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


function softtissue(){
	let element = document.querySelector(".example");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
	var images= images10;
var stack1 = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack1);
}

function bone(){
	let element = document.querySelector(".example");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
var images= imagesbone;
var stack2 = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack2);	
}
function lung(){
	let element = document.querySelector(".example");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
var images= imageslung;
var stack3 = new ImageStack({
  images: images,
  height: '512px',
  width: '512px'
});
document.querySelector('.example').appendChild(stack3);

}