按下时如何突出显示按钮

时间:2016-08-24 08:17:52

标签: javascript d3.js

我有两个图表和两个按钮可以在它们之间切换。

<div class="buttons">
  <button id="DIM1">Dimension_1</button>
  <button id="DIM2">Dimension_2</button>
</div

我想突出显示与选择数据集相关的按钮。此外,我需要首先突出显示第一个,因为第一个数据集显示在开头。

小提琴:https://jsfiddle.net/anton9ov/v72kLebe/

3 个答案:

答案 0 :(得分:2)

我修改了脚本的底部部分:

d3.select("#DIM1")
    .on("click", function() {
        //New values for dataset
        var dataset = [681, 602, 613, 648, 654, 669, 688, 701, 697, 686, 684, 675, 742, 655, 662, 709, 709, 718, 739];

        d3.select('#DIM2').style('background-color', 'initial');
        d3.select(this).style('background-color', '#99ccee');

        transition(dataset, " DIM1")
     });

d3.select("#DIM2")
    .on("click", function() {
        //New values for dataset
        var dataset = [619, 412, 408, 438, 463, 474, 449, 458, 415, 389, 409, 379, 412, 345, 307, 343, 361, 369, 371];

        d3.select('#DIM1').style('background-color', 'initial');
        d3.select(this).style('background-color', '#99ccee');

        transition(dataset, " DIM2")
     });

在“点击”事件中,我只需选择按钮并设置背景颜色属性,然后选择另一个按钮并重置背景颜色属性。

答案 1 :(得分:2)

为css文件创建一个名为“active_btn”的类 将其添加到第一个按钮 单击一个按钮时,删除所有其他按钮的class active_btn,并将其添加到当前按钮。

请参阅代码段以了解

var dataset = [681, 602, 613, 648, 654, 669, 688, 701, 697, 686, 684, 675, 742, 655, 662, 709, 709, 718, 739];
		
		//Width and height
		var w = 620;
		var h = 320;
		var bottomPadding = 40;
    var topPadding = 10;
		var barPadding = 5;
		var barWidth = d3.round(w / dataset.length);

		//Localize numbers, dates, currencies
		var ru_BY = {
			"decimal": ",",
			"thousands": "\xa0",
			"grouping": [3],
			"currency": ["", " Br"],
			"dateTime": "%A, %e %B %Y г. %X",
			"date": "%d.%m.%Y",
			"time": "%H:%M:%S",
			"periods": ["AM", "PM"],
			"days": ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"],
			"shortDays": ["вс", "пн", "вт", "ср", "чт", "пт", "сб"],
			"months": ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
			"shortMonths": ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"]
		};

		//Store locale object
		var RU = d3.locale(ru_BY);

		//Create scale function for bar height
		var yScale = d3.scale.linear()
							 .domain([0, d3.max(dataset)])
							 .rangeRound([bottomPadding, h - topPadding - bottomPadding]);

		//Define x axis
		var minDate = new Date(2014, 11, 1),
			maxDate = new Date(2016, 5, 1);

		var xScale = d3.time.scale()
					   .domain([minDate, maxDate])
					   .range([(barWidth - barPadding) / 2, barWidth * (dataset.length - 1) + (barWidth - barPadding) / 2]);

		var xAxis = d3.svg.axis()
						  .scale(xScale)
						  .orient("bottom")
              //Specify the frequency of ticks
              .ticks(d3.time.months, 1)
              //Specify size of ticks, by default 6
              .tickSize(0)
              .tickFormat(RU.timeFormat("%b %Y"));
		
		//Create SVG element
		var svg = d3.select("body")
					.append("svg")
					.attr("width", w)
					.attr("height", h);
		
		//Create rectangles
		svg.selectAll("rect")
			.data(dataset)
			.enter()
			.append("rect")
			.attr("x", function(d, i) {
			   	return i * barWidth;
			})
			.attr("y", function(d) {
				return h - yScale(d) - bottomPadding;
			})
			.attr("width", barWidth - barPadding)
			.attr("height", function(d) {
				return yScale(d);
			})
			.attr("fill", "red")
      .on("mouseover", function(d, i) {
        var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0];
        console.log (tickDate);
        var formatDate = RU.timeFormat("%B %Y");
        var tooltipDate = formatDate(tickDate);
      	//Get this bar's x/y values, then augment for the tooltip
        var xPosition = parseFloat(d3. select(this). attr("x")) + ((barWidth - barPadding) / 2);
        var yPosition = parseFloat(d3. select(this). attr("y")) / 2 + h / 2;
        //Update the tooltip position and value
        d3.select("#tooltip" )
        	.style("left" , xPosition + "px")
          .style("top" , yPosition + "px")
          .select("#value")
          .text(d + " Br");
				d3.select("#tooltip" )
          .select("#label")
          .text(tooltipDate);
				//Show the tooltip
        d3.select("#tooltip" ).
        	classed("hidden" , false);
				d3.select(this)
        	.attr("fill", "orange");
      })
      .on("mouseout", function(d) {
      	//Hide the tooltip
				d3.select("#tooltip")
        	.classed("hidden" , true);
      	d3.select(this)
        	.transition()
          .duration(150)
        	.attr("fill", "red");
      });

		//Create text
		svg.selectAll("text")
			.data(dataset)
			.enter()
			.append("text")
			.text(function(d) {
				return d;
			})
			.attr("text-anchor", "middle")
			.attr("x", function(d, i) {
			   	return i * barWidth + (barWidth - barPadding) / 2;
			})
			.attr("y", function(d) {
				return h - yScale(d) + 14 - bottomPadding;
			})
			.attr("font-family", "sans-serif")
			.attr("font-size", "11px")
			.attr("fill", "white")
      .style("pointer-events", "none");

		//Add x axis
		svg.append("g")
		   .attr("class", "axis")
		   .attr("transform", "translate(0," + (h - bottomPadding) + ")")
		   .call(xAxis)
       .selectAll(".tick text")
       .call(wrap, 40);
       
    function wrap(text, width) {
    	text.each(function() { 
      	var text = d3.select(this), 
        words = text.text().split(/\s+/).reverse(), 
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, 
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")), 
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) { 
      line.push(word); 
      tspan.text(line.join(" ")); 
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

function transition(dataset, dimension) {
	//Update scale domain
  yScale.domain([0, d3.max(dataset)]);
  //Update all rects
  svg.selectAll("rect")
     .data(dataset)
     .transition(150)
     .attr("y", function(d) {
     		return h - yScale(d) - bottomPadding;
     })
     .attr("height", function(d) {
     		return yScale(d);
     })
     .attr("fill", function(d, i) {
     		return dimension === " DIM1" ? "red" : "blue";
     });
  svg.selectAll("rect")
     .on("mouseover", function(d, i) {
     		var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0];
        var formatDate = RU.timeFormat("%B %Y");
        var tooltipDate = formatDate(tickDate);
      	//Get this bar's x/y values, then augment for the tooltip
        var xPosition = parseFloat(d3. select(this). attr("x")) + ((barWidth - barPadding) / 2);
        var yPosition = parseFloat(d3. select(this). attr("y")) / 2 + h / 2;
        //Update the tooltip position and value
        d3.select("#tooltip" )
        	.style("left" , xPosition + "px")
          .style("top" , yPosition + "px")
          .select("#value")
          .text(d + dimension);          
				d3.select("#tooltip" )
          .select("#label")
          .text(tooltipDate);
				//Show the tooltip
        d3.select("#tooltip" )
          .classed("hidden" , false);
				d3.select(this)
        	.attr("fill", "orange");
     })
     .on("mouseout", function(d) {
      	//Hide the tooltip
				d3.select("#tooltip")
        	.classed("hidden" , true);
      	d3.select(this)
        	.transition()
          .duration(150)
        	.attr("fill", function(d, i) { return dimension === " DIM1" ? "red" : "blue"; } );
      });
  //Update all labels
	svg.selectAll("text")
		 .data(dataset)
     .transition(150)
		 .text(function(d) {
		 		return d;
		 })
		 .attr("x", function(d, i) {
		 		return i * barWidth + (barWidth - barPadding) / 2;
		 })
		 .attr("y", function(d) {
		 		return h - yScale(d) + 14 - bottomPadding;
		 });
}

d3.select("#DIM1")
    .on("click", function() {
        //New values for dataset
        var dataset = [681, 602, 613, 648, 654, 669, 688, 701, 697, 686, 684, 675, 742, 655, 662, 709, 709, 718, 739];
        transition(dataset, " DIM1")
     });
     
d3.select("#DIM2")
    .on("click", function() {
        //New values for dataset
        var dataset = [619, 412, 408, 438, 463, 474, 449, 458, 415, 389, 409, 379, 412, 345, 307, 343, 361, 369, 371];
        transition(dataset, " DIM2")
     });
     
$('.hightlight_btn').click(function(){
	$('.hightlight_btn').removeClass('active_btn');
	$(this).addClass('active_btn');
});
.axis path,
			.axis line {
				fill: none;
				/* stroke: black; */
				shape-rendering: crispEdges;
			}
			
			.axis text {
				font-family: sans-serif;
				font-size: 11px;
			}
      
      #tooltip {
				position: absolute;
				width: auto;
				height: auto;
				padding: 10px;
				background-color: white;
				-webkit-border-radius: 10px;
				-moz-border-radius: 10px;
				border-radius: 10px;
				-webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
				-moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
				box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
				pointer-events: none;
			}
			
			#tooltip.hidden {
				display: none;
			}
			
			#tooltip p {
				margin: 0;
				font-family: sans-serif;
				font-size: 16px;
				line-height: 20px;
			}
      
      .buttons {
        text-align: center;
        width: 620px;
      }
      
      .active_btn {
        background-color: red;
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>


<div id="tooltip" class="hidden">
  <p><strong><span id="label">month</span></strong></p>
  <p><span id="value">100</span></p>
</div>
<div class="buttons">
  <button id="DIM1" class="hightlight_btn active_btn">Dimension_1</button>
  <button id="DIM2" class="hightlight_btn">Dimension_2</button>
</div>

答案 2 :(得分:1)

您可能应该在点击按钮时切换按钮。像这样:

.buttons .active {
   background: red;
}

(你当然会适当地设计它,而不仅仅是把它变成红色......)

然后是这样的,假设你有权访问Jquery:

d3.select("#DIM1")
.on("click", function() {

    $('.buttons button').removeClass('active');
  $(this).addClass('active');

    //New values for dataset
    var dataset = [681, 602, 613, 648, 654, 669, 688, 701, 697, 686, 684, 675, 742, 655, 662, 709, 709, 718, 739];
    transition(dataset, " DIM1")
 });

d3.select("#DIM2")
    .on("click", function() {

    $('.buttons button').removeClass('active');
      $(this).addClass('active');

        //New values for dataset
        var dataset = [619, 412, 408, 438, 463, 474, 449, 458, 415, 389, 409, 379, 412, 345, 307, 343, 361, 369, 371];
        transition(dataset, " DIM2")
     });

如果你不想在这里使用JQuery,那就是d3.js方法:

d3.select("#DIM1")
.on("click", function() {
    d3.select("#DIM1").attr('class', 'active');
  d3.select("#DIM2").attr('class', '');
    //New values for dataset
    var dataset = [681, 602, 613, 648, 654, 669, 688, 701, 697, 686, 684, 675, 742, 655, 662, 709, 709, 718, 739];
    transition(dataset, " DIM1")
 });

d3.select("#DIM2")
    .on("click", function() {
      d3.select("#DIM2").attr('class', 'active');
      d3.select("#DIM1").attr('class', '');
        //New values for dataset
        var dataset = [619, 412, 408, 438, 463, 474, 449, 458, 415, 389, 409, 379, 412, 345, 307, 343, 361, 369, 371];
        transition(dataset, " DIM2")
     });