简体   繁体   中英

Bootstrap get width of div column in pixels

I'm setting up a page with bootstrap. I have the layout working perfectly but one of the elements is a zoomable map of the US (using d3). The zoom function I am using requires the width and height of the div in pixels in order to calculate how to translate and scale the map. I have tried using percentages but I can't get anything going that way. Is there any way to dynamically get the height and width of the div. I have searched all over but the search terms are too generic (or I'm not clever enough to phrase it correctly).

Alternatively, how else might I get the necessary values.

Here is my implementation using hard coded width and height (which won't work if the page resizes).

//make the map element
    var width = 1000;
    var height = 1000;
    var svg = d3.select("#Map")
    .append("svg")
    .attr("id", "chosvg")
    .attr("height", height)
    //.attr("viewBox", "0 0 600 600")
    .attr("width", width)
    .style("preserveAspectRatio", "true");

    cbsa = svg.append("g");
d3.json("data/us-cbsa.json", function(json) {
    cbsa.selectAll("path")
        .attr("id", "cbsa")
        .data(json.features)
        .enter()
        .append("path") 
        .attr("class", data ? quantize : null) //data ? value_if_true : value_if_false -- ternary operator
        .attr("d", path)
        .on("click", clicked);
});

in the clicked() function, I have the zoom like this which works, but only with a certain window width

        cbsa.transition()
        .duration(750)
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
        .style("stroke-width", 1.5 / k + "px");

For clarity, I am ideally loooking for something like: var width = column.width() //or something using percentages

I can include my html as well if it helps.

You can get the width of the column by calling:

var bb = document.querySelector ('#Map')
                    .getBoundingClientRect(),
       width = bb.right - bb.left;

Depending on the browser, the bb might already have an width property. Keep in mind that the column might appear wider because the initial size of the svg is too big, so its parent column might bee, too.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM